1

当我试图获取列表视图的某个日期时出现此错误,当我搜索它时,我发现它的解决方案是使用异步任务,但不知道如何使用它,所以我可以如何使用它我的代码?

这是代码:

package com.example.ms;

import java.util.ArrayList;
import java.util.HashMap;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.example.ms.XMLParser;
import com.example.ms.LazyAdapter;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class PhotosActivity extends Activity {

    ListView list;
    LazyAdapter adapter;
    static final String KEY_SONG = "song"; // parent node
    static final String KEY_ID = "id";
    static final String KEY_TITLE = "title";
    static final String KEY_ARTIST = "artist";
    static final String KEY_DURATION = "duration";
    static final String KEY_THUMB_URL = "thumb_url";
    static final String URL = "http://api.androidhive.info/music/music.xml";

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photos);

        ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

        XMLParser parser = new XMLParser();
        String xml = parser.getXmlFromUrl(URL); // getting XML from URL
        Document doc = parser.getDomElement(xml); // getting DOM element

        NodeList nl = doc.getElementsByTagName(KEY_SONG);

        // looping through all song nodes <song>
                for (int i = 0; i < nl.getLength(); i++) {
                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();
                    Element e = (Element) nl.item(i);
                    // adding each child node to HashMap key => value
                    map.put(KEY_ID, parser.getValue(e, KEY_ID));
                    map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
                    map.put(KEY_ARTIST, parser.getValue(e, KEY_ARTIST));
                    map.put(KEY_DURATION, parser.getValue(e, KEY_DURATION));
                    map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));

                    // adding HashList to ArrayList
                    songsList.add(map);
                }

        list = (ListView) findViewById(R.id.photoslist);

        // Getting adapter by passing xml data ArrayList
        adapter=new LazyAdapter(this, songsList);        
        list.setAdapter(adapter);


        // Click event for single list row
        list.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {


            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.photos, menu);
        return true;
    }

}
4

2 回答 2

1

是的,您必须运行解析代码,尤其是执行 http 调用的调用 parser.getXmlFromUrl(URL); 在一个单独的线程中。即在 AsyncTask 中。因此,将您的代码复制到 AsyncTask.doInBackground() 并从 doInbackground() 返回已解析的列表。在 AsyncTask.onPostExecution(List) 中,您将收到解析后的列表,这是设置 ListView 适配器的正确点,因为此方法将在主 UI 线程上执行。

公共类 PhotosActivity 扩展 Activity {

private XmlParserTask task;

public void onCreate(Bundle saved){
     super.onCreate(Bundle saved);
    // Do your UI setup
    task = new XmlParserTask();
    task.execute(URL);
 }


public void onDestroy(){
    super.onDestroy();
    // Avoid Memory leaks and android view not attached to window manager Exceptions
    if (task != null)
        task.cancel(true);
 }


private class XmlParserTask extends AsyncTask<String, Void, List<YouSongType>> {

     public List<YourSongType> doInBackground(String ... params){

         String url = params[0];

         List<YourSongType> resultList = new ArrayList<YourSongType>();

        XMLParser parser = new XMLParser();
        String xml = parser.getXmlFromUrl(URL); // getting XML from URL
        Document doc = parser.getDomElement(xml); // getting DOM element

        NodeList nl = doc.getElementsByTagName(KEY_SONG);

       // Add your xml parsed data in the list
       resultList.add();

       return resultList;
    }


   public void onPostExecution(List<YourSongType> songsList){
      adapter=new LazyAdapter(this, songsList);        
      list.setAdapter(adapter);
    }


}
于 2013-10-06T09:25:01.087 回答
0

您收到此错误是因为您试图从网络中获取数据并且您在主线程上执行此操作!

`String xml = parser.getXmlFromUrl(URL);`

正如您所说,您需要触发任何类型的线程以避免主线程上的长时间处理,其中一个选项是 AsyncTask,使用 AsyncTask 很简单,基本上您有三种方法onPreExecute() doInBackground()onPostExecute()

onPreExecute()onPostExecute()在 UI 线程上运行,您可以使用它们来显示对话框、结果或从您的 xml 数据中提供您的列表

doInBackground()在 netowrk 线程上运行,以便您实现从服务器获取 xml,您可以onPostExcute()使用委托从结果中更新您的列表doInBackground()

于 2013-10-06T09:40:32.007 回答