ArrayList不显示发生数据存储的方法之外的值

时间:2016-07-26 03:16:44

标签: java android arraylist

我有这个类,它处理XML并将其存储在ArrayList<FeedItem>中。我可以在存储数据的方法中显示数组内容,但是当我尝试在另一个方法中显示数组时,它没有通过if检查,表明ArrayList为空。因此,我无法创建ListView,因为它会返回相同的错误。我希望有人可以简单地向我解释什么是错的。

ReadRSS.java

public class ReadRSS extends AsyncTask<Void, Void, Void> {

//Initialize progress dialog
Context context;
String address;
ProgressDialog progressDialog;
XmlPullParserFactory xmlPullParserFactory;
volatile boolean parsingComplete = true;
ArrayList<FeedItem> feedItems;
ListView listView;

public ReadRSS(Context context, ListView listView, String retrieveAddress) {
    //Create a new progress dialog
    this.listView = listView;
    this.address = retrieveAddress;
    this.context = context;
    progressDialog = new ProgressDialog(context);
    progressDialog.setMessage("Loading....");

}

// Runs in UI before background thread is called
@Override
protected void onPreExecute() {
    //Display progress dialog
    progressDialog.show();
    super.onPreExecute();
}

// This is run in a background thread
@Override
protected Void doInBackground(Void... voids) {
    fetchXML();
    return null;
}

// This is called from background thread but runs in UI
@Override
protected void onProgressUpdate(Void... values) {
    super.onProgressUpdate(values);
}

// This runs in UI when background thread finishes
@Override
protected void onPostExecute(Void aVoid) {
    //Dismiss progress dialog
    super.onPostExecute(aVoid);
    progressDialog.dismiss();


    /*if(listView != null) {
    CustomAdapter customAdapter = new CustomAdapter(context, R.layout.activity_listview, feedItems);
    listView.setAdapter(customAdapter);

    }*/

   if(feedItems != null){
    //Gives error
        for(int i = 0; i < feedItems.size(); i++) {
            Log.d("Title", feedItems.get(i).getTitle());
            Log.d("Date", feedItems.get(i).getPubDate());
        }

    }

}

//New Build

public void parseXMLAndStoreIt(XmlPullParser myParser) {
    int event;
    String text;
    String title = null;
    String date = null;

    feedItems = new ArrayList<FeedItem>();

    try {
        event = myParser.getEventType();

        while (event != XmlPullParser.END_DOCUMENT) {
            String tagName = myParser.getName();

            switch (event){

                case XmlPullParser.START_TAG:
                    if(tagName.equalsIgnoreCase("item")){
                        int eventChild = myParser.next();
                        //int innerLoop = 1;

                        String tagNameChild = "";
                            while(eventChild != XmlPullParser.END_DOCUMENT){

                                if(eventChild == XmlPullParser.START_TAG){
                                    tagNameChild = myParser.getName();
                                    // Output Test
                                    //Log.d("Tag ", tagNameChild);
                                }

                                else if (eventChild == XmlPullParser.TEXT){

                                    text = myParser.getText();
                                    // Output Test
                                    //Log.d("Test ", text);


                                    if(tagNameChild.equalsIgnoreCase("title")){

                                        title = text;
                                        // Output Test
                                        //Log.d("Title ", myParser.getText());
                                    }
                                    else if(tagNameChild.equalsIgnoreCase("pubDate")){

                                        date = text;
                                        // Output Test
                                        //Log.d("PubDate ", myParser.getText());

                                    }
                                }

                                else if (eventChild == XmlPullParser.END_TAG){


                                    if(myParser.getName().equalsIgnoreCase("item")){

                                        feedItems.add(new FeedItem(title,date));
                                        // Output Test
                                        //Log.d("Test ", title);
                                    }

                                    tagNameChild = "";

                                }

                                eventChild = myParser.next();

                            //innerLoop++;
                            }

                        //Output Test
                        /*for(int i = 0; i < feedItems.size(); i++) {
                            Log.d("Title", feedItems.get(i).getTitle());
                            Log.d("Date", feedItems.get(i).getPubDate());
                        }*/
                    }

                    break;

                case XmlPullParser.TEXT:
                    break;

                case XmlPullParser.END_TAG:
                    break;

            }

            event = myParser.next();

        }

        parsingComplete = false;
    }

    catch (Exception e) {
        e.printStackTrace();
    }
}

public void fetchXML(){
    Thread thread = new Thread(new Runnable(){
        @Override
        public void run() {

            try {
                URL url = new URL(address);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();

                conn.setReadTimeout(10000 );
                conn.setConnectTimeout(15000 );
                conn.setRequestMethod("GET");
                conn.setDoInput(true);

                // Starts the query
                conn.connect();
                InputStream stream = conn.getInputStream();

                xmlPullParserFactory = XmlPullParserFactory.newInstance();
                XmlPullParser myparser = xmlPullParserFactory.newPullParser();

                myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
                myparser.setInput(stream, null);

                parseXMLAndStoreIt(myparser);
                stream.close();
            }

            catch (Exception e) {
            }
        }
    });
    thread.start();
}
}

1 个答案:

答案 0 :(得分:4)

您正在从fetchXML()呼叫doInBackground,但fetchXML()启动新线程,然后立即返回。然后doInBackground()立即返回并调用onPostExecute()。但是,此时fetchXML()启动的主题没有时间完成,因此feedItems尚未正确设置。

这是使用AsyncTask的错误方法。相反,您应该直接在doInBackground()线程中进行提取。只需重写fetchXML()来自己进行提取,而不是启动一个单独的线程来进行提取。