简体   繁体   English

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

[英]Android App showing blank screen on first launch but showing the content on relaunch

I am new to android app development. 我是android应用程序开发的新手。

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. 我编写了一个应用程序来读取XML源并将其显示在屏幕上。 For displaying I had created the LinearLayout, ScrollView ,buttons and textviews dynamically. 为了显示,我动态创建了LinearLayout,ScrollView,按钮和文本视图。 I had used the async task to read the XML data using SAX Parser. 我曾使用async任务通过SAX Parser读取XML数据。

MainActivity.Java 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 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 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 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>

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). 您正在onCreate中使用FetchFeed任务,但是在开始填充数据之前,您并没有等待它完成(因此,在生成视图时,NewsList单例仍然具有空数组)。 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. 到第二次打开“活动”时,任务已经完成,因此在调用onCreate()之前,NewsList中已经有数据。

You need to move all the code that is below new FetchFeed().execute(); 您需要将所有位于new FetchFeed().execute();下面的代码移到new FetchFeed().execute(); in onCreate() into onPostExecute(Void param) in your FetchFeed task. 在onCreate()到FetchFeed任务的onPostExecute(Void param)中。

And where you removed the code in onCreate(), you could replace it with code that displays a progress spinner view. 在onCreate()中删除了代码的地方,可以用显示进度条视图的代码替换它。

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

}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM