1

我是 android 应用程序开发的新手。

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

我想知道为什么它没有在第一次加载时加载。

任何帮助深表感谢....

应用详情:

我编写了一个应用程序来读取 XML 源并将其显示在屏幕上。为了显示,我动态创建了 LinearLayout、ScrollView、buttons 和 textviews。我曾使用异步任务通过 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)
            {

    }

}
}

新闻列表.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);
}

}

新闻XMLHandler.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>
4

2 回答 2

1

您在 onCreate 中使用了 FetchFeed 任务,但在开始填写数据之前您没有等待它完成(因此在生成视图时,您的 NewsList 单例仍然有空数组)。它在您第二次打开应用程序时变得可见,因为您使用的是在关闭 Activity 后仍然存在的单例。当您第二次打开 Activity 时,任务已经完成,所以在调用 onCreate() 之前 NewsList 中已经有数据了。

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

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

于 2013-08-13T18:27:31.197 回答
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());
            }
        }
    }

}
}
于 2013-08-14T06:01:03.743 回答