从ArrayList到Listview的数据

时间:2016-03-22 16:49:14

标签: java android listview arraylist

简单地说,我正在从班级的外部RSS XML中检索数据' HandleXML' (称为MainActivity形式),将其解析/存储在ArrayList中,然后将其输出到Listview。我理解需要一个适配器来将ListList值传递给Listview,但出于某种原因,我不会将数据解析到比ArrayList更远的地方。 我想我有所有组件,也许只是放置不正确?

[编辑] 为了澄清,当按下活动中的任一按钮时,logcat会使用HandleXML.printItems报告空异常。 ArrayList似乎已填充,但Listview中没有任何内容。

*如果它看起来像家庭作业,这是我用来学习自己的其他人。我是一个不是学生的爱好者。

感谢任何帮助。

MainActivity.java

//define buttons
        b1=(Button)findViewById(R.id.b1);
        b2=(Button)findViewById(R.id.b2);

        //on-click listeners for buttons; retrieve XML info
        b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                obj = new HandleXML(roadsURL);
                obj.fetchXML();
            }
        });

        b2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                obj = new HandleXML(proadsURL);
                obj.fetchXML();
            }
        });

HandleXML.java

public class HandleXML extends Activity {

    private static final String TAG = HandleXML.class.getSimpleName(); //Logcat tag for debugging
    private String urlString = null;
    private XmlPullParserFactory xmlFactoryObject;

    public HandleXML(String url){
        this.urlString = url;
    }

    public void parseXMLAndStoreIt(XmlPullParser myParser) {
        int event;
        ArrayList<Item> items = new ArrayList(); //arraylist for item objects
        String text = null;
        Item currentItem = null;

        try {
            event = myParser.getEventType(); //return event type from XML

            while (event != XmlPullParser.END_DOCUMENT) {
                String name = null;

                switch (event){
                    case XmlPullParser.START_DOCUMENT:
                        break;

                    case XmlPullParser.START_TAG: //parse by item tag, then by sub-tags
                        name = myParser.getName();
                        if (name.equals("item")){
                            currentItem = new Item(); //new item object for arraylist
                        } else if (currentItem != null){
                            if (name.equals("title")){
                                currentItem.title = text;
                            } else if (name.equals("description")){
                                currentItem.description = text;
                            } 
                        }
                        break;

                    case XmlPullParser.TEXT:
                        text = myParser.getText(); //retrieve text value from tag
                        break;

                    case XmlPullParser.END_TAG:

                        name = myParser.getName();
                        if (name.equalsIgnoreCase("item") && currentItem != null) {
                            items.add(currentItem); //add to arraylist
                            //Log.e(TAG, "parse: added new item "); //DEBUG - print the code to logcat
                        }
                }

                event = myParser.next();
            }
            printItems(items); //get arraylist info to screen
        }

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

    private void printItems(ArrayList<Item> items)
    {
        ListView lv = (ListView)findViewById(R.id.info); //scroll area listview

        //adapter with pre-defined layout for listview, source arraylist
        ArrayAdapter<Item> adapter = new ArrayAdapter<Item>(this, android.R.layout.simple_list_item_2 , items);
        lv.setAdapter(adapter); //link adapter to listview
    }

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

                try {
                    URL url = new URL(urlString);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    //HttpURLConnection settings
                    conn.setReadTimeout(10000 /* milliseconds */);
                    conn.setConnectTimeout(15000 /* milliseconds */);
                    conn.setAllowUserInteraction(false);
                    conn.setInstanceFollowRedirects(true);
                    conn.setRequestMethod("GET");
                    conn.setDoInput(true);

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

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

                    myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
                    myparser.setInput(stream, null); //set XML source as stream

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

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

2 个答案:

答案 0 :(得分:0)

在代码中的单击侦听器中,您正在创建扩展Activity.java obj = new HandleXML(proadsURL);的类的对象。这不应该这样做。它不是我们,最终用户(使用Android框架来设计我们的应用程序)创建Activity的人。它是创建Activity并管理其生命周期的框架。我们在AndroidMenifest.xml中注册我们的Activity,然后我们就可以开始活动了。

我建议您了解Activity的生命周期。 Android框架设计精美,为活动生命周期提供回调方法。 http://developer.android.com/training/basics/activity-lifecycle/index.html

我们应set contentView为活动。在contentView中,您需要挂钩ListView

我们还需要在AndroidMenifest.xml中定义我们的Launcher活动。如果您希望在某些事件发生时启动另一项活动,那么您应该研究如何使用startActivity方法。

http://themasterworld.com/starting-new-activity-on-button-click-android/

同样尊重SRP原则(单一责任原则),我建议您不要在活动中解析XML。请勿将其用于此唯一目的。 Activity是提供用户界面。

答案 1 :(得分:0)

我认为您应该考虑使用ASYNC任务,因为您可以比标准线程更精确地控制数据流。您可以传入对列表视图的引用,并在onPostExecute()

中更新它

考虑一下:

        //on-click listeners for buttons; retrieve XML info
        b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new DownloadFilesTask(listview_item_or_adapter_reference).execute(roadsURL);
            }
        });


 private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {

     private static final String TAG = HandleXML.class.getSimpleName();                 
     //Logcat tag for debugging
     private String urlString = null;
     private XmlPullParserFactory xmlFactoryObject;
     private ListView item;

     public DownloadFilesTask(ListView item){
     this.item = item;
     }

     protected String doInBackground(URL... urls) {
 try {
                    URL url = new URL(urlString);
                    HttpURLConnection conn = (HttpURLConnection) 
                    url.openConnection();
                    //HttpURLConnection settings
                    conn.setReadTimeout(10000 /* milliseconds */);
                    conn.setConnectTimeout(15000 /* milliseconds */);
                    conn.setAllowUserInteraction(false);
                    conn.setInstanceFollowRedirects(true);
                    conn.setRequestMethod("GET");
                    conn.setDoInput(true);

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

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

                    myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
                    myparser.setInput(stream, null); //set XML source as stream


                    stream.close();
                }

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

     protected void onPostExecute(String result) {
         showDialog("Downloaded  data,pasring now...");
         parseXMLAndStoreIt(myparser);
         //update item or adapter here
     }






       private void printItems(ArrayList<Item> items)
    {
        ListView lv = (ListView)findViewById(R.id.info); //scroll area listview

        //adapter with pre-defined layout for listview, source arraylist
        ArrayAdapter<Item> adapter = new ArrayAdapter<Item>(this, android.R.layout.simple_list_item_2 , items);
        lv.setAdapter(adapter); //link adapter to listview
    }

      public void parseXMLAndStoreIt(XmlPullParser myParser) {
        int event;
        ArrayList<Item> items = new ArrayList(); //arraylist for item objects
        String text = null;
        Item currentItem = null;

        try {
            event = myParser.getEventType(); //return event type from XML

            while (event != XmlPullParser.END_DOCUMENT) {
                String name = null;

                switch (event){
                    case XmlPullParser.START_DOCUMENT:
                        break;

                    case XmlPullParser.START_TAG: //parse by item tag, then by sub-tags
                        name = myParser.getName();
                        if (name.equals("item")){
                            currentItem = new Item(); //new item object for arraylist
                        } else if (currentItem != null){
                            if (name.equals("title")){
                                currentItem.title = text;
                            } else if (name.equals("description")){
                                currentItem.description = text;
                            } 
                        }
                        break;

                    case XmlPullParser.TEXT:
                        text = myParser.getText(); //retrieve text value from tag
                        break;

                    case XmlPullParser.END_TAG:

                        name = myParser.getName();
                        if (name.equalsIgnoreCase("item") && currentItem != null) {
                            items.add(currentItem); //add to arraylist
                            //Log.e(TAG, "parse: added new item "); //DEBUG - print the code to logcat
                        }
                }

                event = myParser.next();
            }
            printItems(items); //get arraylist info to screen
        }

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

 }