如何使用AsyncTask for CustimizedListView

时间:2014-06-04 04:38:15

标签: android android-asynctask

我如何在本教程中为以下类实现AsyncTask:http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/

如何在以下类中实现AsyncTask:

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

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

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class CustomizedListView extends Activity {
    // All static variables
    static final String URL = "http://api.androidhive.info/music/music.xml";
    // XML node keys
    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";

    ListView list;
    LazyAdapter adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.menu_page);


            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(android.R.id.list);

            // 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) {


                    }
            });     
    }   
}

我尝试使用AsyncTask的原因是因为我收到错误:android.os.NetworkOnMainThreadException

3 个答案:

答案 0 :(得分:1)

你应该改变这个

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

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

并确保ListView布局中id list menu_page

您还应该使用AsyncTask

在后台进行与网络相关的工作

参考此NetWork On main thread Exception

和/或android os network on main thread exception

AsyncTask 演示

参考此http://www.compiletimeerror.com/2013/01/why-and-how-to-use-asynctask.html

和/或http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html

答案 1 :(得分:0)

试试这个..

初始化ListView调用registerInBackground()方法

如下所示

@Override
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.menu_page);


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

        registerInBackground();


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

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


                }
        });     
}   

registerInBackground方法

    private void registerInBackground() {

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

        new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {                   

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

                return "finished";
            }

            @Override
            protected void onPostExecute(String msg) {
                // Getting adapter by passing xml data ArrayList
        adapter=new LazyAdapter(this, songsList);        
        list.setAdapter(adapter);
            }
        }.execute(null, null, null);
    }

答案 2 :(得分:0)

在创建方法之后:

 class MyRequest extends AsyncTask<Object, Object, Object>{

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        // do Stuff before the request Example show a dialog...
    }



    @Override
    protected Object doInBackground(Object... params) {

        // DO your network request here

        return null;
    }

    @Override
    protected void onPostExecute(Object o) {
        super.onPostExecute(o);

        // Handle your request here, dismiss any dialogs and update the UI thread.

    }
}

他们可以使用new MyRequest().execute();

从您的UI线程调用类