Question

I am new to android app development.

The problem I am facing is , on first run my app is showing blank screen, when I close it and reopen it immediately, it is working correctly.

I am wondering why it is not loading on the first go.

Any help is much appreciated....

App details:

I had written an app to read an XML source and display it on screen. For displaying I had created the LinearLayout, ScrollView ,buttons and textviews dynamically. I had used the async task to read the XML data using SAX Parser.

MainActivity.Java

package com.example.thehindu_topstories;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.Menu;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

public class MainActivity extends Activity
{
NewsList newsList = null;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    ScrollView sv = new ScrollView(this);
    LinearLayout layout = new LinearLayout(this);       



    sv.addView(layout);


    layout.setOrientation(LinearLayout.VERTICAL);



    new FetchFeed().execute();


    Button title[];
    TextView pubDate[];


    newsList = NewsXMLHandler.newsList;
    title = new Button[newsList.getTitle().size()];

    pubDate = new TextView[newsList.getpubDate().size()];

    for (int i = 1; i <= (newsList.getTitle().size()); i++)
    {

        try{

                title[i] = new Button(this);
                title[i].setText(i+"."+newsList.getTitle().get(i)+"\n");

                title[i].append(Html.fromHtml( String.format("<a href=\"%s\">(..Read more..)</a> ",newsList.getLink().get(i))));
                title[i].setMovementMethod(LinkMovementMethod.getInstance());

                title[i].setBackgroundColor(Color.LTGRAY);
                pubDate[i]= new TextView(this);
                pubDate[i].setText(newsList.getpubDate().get(i)+"\n");

                pubDate[i].setTextSize(10);

                layout.addView(title[i]);

                layout.addView(pubDate[i]);

            }
            catch(Exception e)
            {
                    System.out.println(e.toString());
            }
        }
    setContentView(sv); 
}

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

private class FetchFeed extends AsyncTask<Void, Void, Void>
{

    protected Void doInBackground(Void... params)
    {
        try
        {
            SAXParserFactory spf=SAXParserFactory.newInstance();
            SAXParser sp= spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();
            URL SourceUrl = new URL ("http://beta.thehindu.com/news/?service=rss");

            NewsXMLHandler myXMLHandler = new NewsXMLHandler();
            xr.setContentHandler(myXMLHandler);
            xr.parse(new InputSource(SourceUrl.openStream()));
        }
        catch (ParseException e)
        {
            System.out.println("XML Parsing Exception="+ e);
        }

        catch (MalformedURLException e)
        {
            System.out.println("XML Parsing Exception="+ e);
        }
        catch (Exception e)
        {
            System.out.println("XML Parsing Exception="+ e);
        }
        return null;
        /**/
    }
    protected void onPostExecute(Void param)
            {

    }

}
}

NewsList.Java

package com.example.thehindu_topstories;

import java.util.ArrayList;

public class NewsList
{
private ArrayList<String> title = new ArrayList<String>();
private ArrayList<String> link = new ArrayList<String>();
private ArrayList<String> pubDate = new ArrayList<String>();

public ArrayList<String> getTitle()
{
    return title;
}

public void setTitle(String title)
{
    this.title.add(title);
}

public ArrayList<String> getLink()
{
    return link;
}

public void setLink(String link)
{
    this.link.add(link);
}


public ArrayList<String> getpubDate()
{
    return pubDate;
}

public void setpubDate(String pubDate)
{
    this.pubDate.add(pubDate);
}

}

NewsXMLHandler.java

package com.example.thehindu_topstories;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class NewsXMLHandler extends DefaultHandler
{


Boolean currentElement = false;
String currentValue = null;
public static NewsList newsList = new NewsList();

public static NewsList getNewsList()
{
return newsList;
}

public static void setNewsList(NewsList newsList)
{
    NewsXMLHandler.newsList = newsList;
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException
{

    currentElement = true;

    if (localName.equals("channel"))
    {
        newsList = new NewsList();
    }

}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException
{

    currentElement = false;

    if (localName.equalsIgnoreCase("title"))
        newsList.setTitle(currentValue);
    else if (localName.equalsIgnoreCase("link"))
        newsList.setLink(currentValue);
    else if (localName.equalsIgnoreCase("pubDate"))
        newsList.setpubDate(currentValue);


}

@Override
public void characters(char[] ch, int start, int length)
throws SAXException
{

    if (currentElement)
    {
        currentValue = new String(ch, start, length);
        currentElement = false;
    }

}



}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >


</RelativeLayout>
Was it helpful?

Solution 2

Try this code:

package com.example.thehindu_topstories;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.Menu;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

public class MainActivity extends Activity
{
NewsList newsList = null;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    ScrollView sv = new ScrollView(this);
    LinearLayout layout = new LinearLayout(this);       

    setContentView(sv); 


    sv.addView(layout);


    layout.setOrientation(LinearLayout.VERTICAL);



    new FetchFeed().execute();

}

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

private class FetchFeed extends AsyncTask<Void, Void, Void>
{

    protected Void doInBackground(Void... params)
    {
        try
        {
            SAXParserFactory spf=SAXParserFactory.newInstance();
            SAXParser sp= spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();
            URL SourceUrl = new URL ("http://beta.thehindu.com/news/?service=rss");

            NewsXMLHandler myXMLHandler = new NewsXMLHandler();
            xr.setContentHandler(myXMLHandler);
            xr.parse(new InputSource(SourceUrl.openStream()));
        }
        catch (ParseException e)
        {
            System.out.println("XML Parsing Exception="+ e);
        }

        catch (MalformedURLException e)
        {
            System.out.println("XML Parsing Exception="+ e);
        }
        catch (Exception e)
        {
            System.out.println("XML Parsing Exception="+ e);
        }
        return null;
        /**/
    }
    protected void onPostExecute(Void param)
            {

    Button title[];
    TextView pubDate[];


    newsList = NewsXMLHandler.newsList;
    title = new Button[newsList.getTitle().size()];

    pubDate = new TextView[newsList.getpubDate().size()];

    for (int i = 1; i <= (newsList.getTitle().size()); i++)
    {

        try{

                title[i] = new Button(this);
                title[i].setText(i+"."+newsList.getTitle().get(i)+"\n");

                title[i].append(Html.fromHtml( String.format("<a href=\"%s\">(..Read more..)</a> ",newsList.getLink().get(i))));
                title[i].setMovementMethod(LinkMovementMethod.getInstance());

                title[i].setBackgroundColor(Color.LTGRAY);
                pubDate[i]= new TextView(this);
                pubDate[i].setText(newsList.getpubDate().get(i)+"\n");

                pubDate[i].setTextSize(10);

                layout.addView(title[i]);

                layout.addView(pubDate[i]);

            }
            catch(Exception e)
            {
                    System.out.println(e.toString());
            }
        }
    }

}
}

OTHER TIPS

You are using the FetchFeed task in onCreate, but you are not waiting for it to finish before you start filling in the data (so your NewsList singleton still has empty arrays when the views are being generated). It becomes visible the second time you open your app because you are using a singleton that survives closing the Activity. By the time you open your Activity a second time, the task has been completed, so now there is already data in NewsList before onCreate() is called.

You need to move all the code that is below new FetchFeed().execute(); in onCreate() into onPostExecute(Void param) in your FetchFeed task.

And where you removed the code in onCreate(), you could replace it with code that displays a progress spinner view.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top