Android App在首次启动时显示空白屏幕,但在重新启动时显示内容

时间:2013-08-13 14:21:29

标签: android android-layout launch

我是Android应用开发的新手。

我面临的问题是,首次运行时,我的应用程序显示空白屏幕,当我关闭它并立即重新打开时,它正常工作。

我想知道它为什么不在第一次加载。

非常感谢任何帮助......

应用详情:

我编写了一个应用程序来读取XML源并在屏幕上显示它。为了显示,我动态创建了LinearLayout,ScrollView,按钮和textview。我曾使用异步任务使用SAX Parser读取XML数据。

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>

2 个答案:

答案 0 :(得分:1)

您正在onCreate中使用FetchFeed任务,但在开始填充数据之前,您并没有等待它完成(因此,在生成视图时,您的NewsList单例仍然具有空数组)。它会在您第二次打开应用程序时变得可见,因为您正在使用一个单独的活动关闭。当你第二次打开你的Activity时,任务已经完成,所以现在在调用onCreate()之前,NewsList中已有数据。

您需要将onCreate()中new FetchFeed().execute();以下的所有代码移动到FetchFeed任务中的onPostExecute(Void param)

在onCreate()中删除代码的位置,您可以将其替换为显示进度微调器视图的代码。

答案 1 :(得分:0)

试试这段代码:

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());
            }
        }
    }

}
}