使用AsyncTask加载数据



我需要你的帮助。我们必须读取XML文件并将数据加载到ListView中。使用AsyncTask最好的方法是什么?

private class ListaEventosTask extends AsyncTask<Void, Void, LinkedList<Map<String,?>>> {
    @Override
    protected LinkedList<Map<String,?>> doInBackground(Void... params) {
        xml = AuxXMLfunctions.getXML("http://xxx.com/list.php");
        doc = AuxXMLfunctions.XMLfromString(xml);
        List<Map<String,?>> listaItens = new LinkedList<Map<String,?>>(); 
        NodeList nodes = doc.getElementsByTagName("evento");
        for (int i = 0; i < nodes.getLength(); i++) {    
            Element e = (Element)nodes.item(i);
                listaItens.add(createItem(AuxXMLfunctions.getValue(e, "nome"),AuxXMLfunctions.getValue(e, "qtde_atividades") + " atividades programadas",AuxXMLfunctions.getValue(e, "codigo"),"0"));               
        }   
        return (LinkedList<Map<String, ?>>) listaItens;
    }       
这是onPostExecute代码:
    @Override 
    protected void onPostExecute(LinkedList<Map<String,?>> result) {
        adapter.addSection("Selecione o evento", new SimpleAdapter(ListViewEventos.this, result, R.layout.lista, new String[] {ITEM_TITLE, ITEM_CAPTION}, new int[] { R.id.list_complex_title, R.id.list_complex_caption}));
        list.setAdapter(adapter);
        ListViewEventos.this.setContentView(list);
        super.onPostExecute(result);
    }

那么现在,我有下面的异常:

03-30 18:33:21.889: E/AndroidRuntime(605): Uncaught handler: thread main exiting due to uncaught exception
03-30 18:33:21.909: I/Teste(605): Evento não encontrado
03-30 18:33:21.909: E/AndroidRuntime(605): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{br.com.lwu.eventus/br.com.lwu.eventus.ListViewEventos}: java.lang.NullPointerException
03-30 18:33:21.909: E/AndroidRuntime(605):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2417)
03-30 18:33:21.909: E/AndroidRuntime(605):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
03-30 18:33:21.909: E/AndroidRuntime(605):  at android.app.ActivityThread.access$2200(ActivityThread.java:119)
03-30 18:33:21.909: E/AndroidRuntime(605):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
03-30 18:33:21.909: E/AndroidRuntime(605):  at android.os.Handler.dispatchMessage(Handler.java:99)
03-30 18:33:21.909: E/AndroidRuntime(605):  at android.os.Looper.loop(Looper.java:123)
03-30 18:33:21.909: E/AndroidRuntime(605):  at android.app.ActivityThread.main(ActivityThread.java:4363)
03-30 18:33:21.909: E/AndroidRuntime(605):  at java.lang.reflect.Method.invokeNative(Native Method)
03-30 18:33:21.909: E/AndroidRuntime(605):  at java.lang.reflect.Method.invoke(Method.java:521)
03-30 18:33:21.909: E/AndroidRuntime(605):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
03-30 18:33:21.909: E/AndroidRuntime(605):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
03-30 18:33:21.909: E/AndroidRuntime(605):  at dalvik.system.NativeStart.main(Native Method)
03-30 18:33:21.909: E/AndroidRuntime(605): Caused by: java.lang.NullPointerException
03-30 18:33:21.909: E/AndroidRuntime(605):  at android.content.ContextWrapper.getResources(ContextWrapper.java:80)
03-30 18:33:21.909: E/AndroidRuntime(605):  at android.view.View.<init>(View.java:1777)
03-30 18:33:21.909: E/AndroidRuntime(605):  at android.view.View.<init>(View.java:1821)
03-30 18:33:21.909: E/AndroidRuntime(605):  at android.view.ViewGroup.<init>(ViewGroup.java:290)
03-30 18:33:21.909: E/AndroidRuntime(605):  at android.widget.AdapterView.<init>(AdapterView.java:228)
03-30 18:33:21.909: E/AndroidRuntime(605):  at android.widget.AbsListView.<init>(AbsListView.java:508)
03-30 18:33:21.909: E/AndroidRuntime(605):  at android.widget.ListView.<init>(ListView.java:152)
03-30 18:33:21.909: E/AndroidRuntime(605):  at android.widget.ListView.<init>(ListView.java:148)
03-30 18:33:21.909: E/AndroidRuntime(605):  at android.widget.ListView.<init>(ListView.java:144)
03-30 18:33:21.909: E/AndroidRuntime(605):  at br.com.lwu.eventus.ListViewEventos.<init>(ListViewEventos.java:54)
03-30 18:33:21.909: E/AndroidRuntime(605):  at java.lang.Class.newInstanceImpl(Native Method)
03-30 18:33:21.909: E/AndroidRuntime(605):  at java.lang.Class.newInstance(Class.java:1479)
03-30 18:33:21.909: E/AndroidRuntime(605):  at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
03-30 18:33:21.909: E/AndroidRuntime(605):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2409)
03-30 18:33:21.909: E/AndroidRuntime(605):  ... 11 more
下面是ListViewEventos的部分代码:
public class ListViewEventos extends Activity {
public final static String ITEM_TITLE   = "title";
public final static String ITEM_CAPTION = "caption";
public final static String ITEM_ID      = "id";
public final static String ITEM_LISTA   = "lista";
public Map<String,?> createItem(String title, String caption, String id, String lista) {
    Map<String,String> item = new HashMap<String,String>();
    item.put(ITEM_TITLE, title);
    item.put(ITEM_CAPTION, caption);        
    item.put(ITEM_ID, id);
    item.put(ITEM_LISTA, lista);
    return item;
}
String xml;
Document doc;
NodeList nodes;
String codEvento, nomeEvento;
AuxDAO         myDAO           = new AuxDAO(this);
AuxUtilitarios meusUtilitarios = new AuxUtilitarios(this);
ListView       list            = new ListView(this);
BaseAdapterListas adapter      = new BaseAdapterListas(this);
private ProgressDialog progressDialog;
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    list.setBackgroundColor(Color.WHITE);
    list.setCacheColorHint(Color.WHITE);
    list.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> a, View v, final int position, long id) {
            @SuppressWarnings("unchecked")
            HashMap<String, String> objSelecionado = (HashMap<String, String>) list.getItemAtPosition(position);
            // 1 - Sincroniza a programação do evento selecionado:
            importaProgramacao(objSelecionado.get("id"));
            // 2 - Armazena o código da Unidade e o seu nome para serem passados para o Menu Principal:
            codEvento  = objSelecionado.get("id");
            nomeEvento = objSelecionado.get("title");
        }
    });            

    // Verifica se existe rede disponível:
    if (meusUtilitarios.haveInternet(this)) {
        try {
            ListaEventosTask asyncTask = new ListaEventosTask();
            asyncTask.execute(); 
        } catch (Exception e) {
            Log.i("Teste", "Erro: " + e);
        }

    }
    else {
        Toast.makeText(ListViewEventos.this, "Sem conexão à Internet", Toast.LENGTH_LONG).show();
        finish();
    }                       
}
private class ListaEventosTask extends AsyncTask<Void, Void, LinkedList<Map<String,?>>> {
    @Override
    protected LinkedList<Map<String,?>> doInBackground(Void... params) {
        xml = AuxXMLfunctions.getXML("http://kanegae.com.br/eventus/api/1.0/eventos.php");
        doc = AuxXMLfunctions.XMLfromString(xml);
        List<Map<String,?>> listaItens = new LinkedList<Map<String,?>>(); 
        NodeList nodes = doc.getElementsByTagName("evento");
        for (int i = 0; i < nodes.getLength(); i++) {    
            Element e = (Element)nodes.item(i);
                listaItens.add(createItem(AuxXMLfunctions.getValue(e, "nome"),AuxXMLfunctions.getValue(e, "qtde_atividades") + " atividades programadas",AuxXMLfunctions.getValue(e, "codigo"),"0"));               
        }   
        return (LinkedList<Map<String, ?>>) listaItens;
    }       
    @Override 
    protected void onPostExecute(LinkedList<Map<String,?>> result) {
        adapter.addSection("Selecione o evento", new SimpleAdapter(ListViewEventos.this, result, R.layout.lista, new String[] {ITEM_TITLE, ITEM_CAPTION}, new int[] { R.id.list_complex_title, R.id.list_complex_caption}));
        list.setAdapter(adapter);
        ListViewEventos.this.setContentView(list);
        super.onPostExecute(result);
    }       
}   
.
.
.
.   
}

解决。但是,我不知道这是否是最好的方法。请看下面的代码:

public void onCreate(Bundle icicle) {
        super.onCreate(icicle);     
        myDAO           = new AuxDAO(this);
        meusUtilitarios = new AuxUtilitarios(this);     
        adapter         = new BaseAdapterListas(this);          
        list            = new ListView(this);
        list.setBackgroundColor(Color.WHITE);
        list.setCacheColorHint(Color.WHITE);
        list.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> a, View v, final int position, long id) {
                @SuppressWarnings("unchecked")
                HashMap<String, String> objSelecionado = (HashMap<String, String>) list.getItemAtPosition(position);
                // 1 - Sincroniza a programação do evento selecionado:
                importaProgramacao(objSelecionado.get("id"));
                // 2 - Armazena o código da Unidade e o seu nome para serem passados para o Menu Principal:
                codEvento  = objSelecionado.get("id");
                nomeEvento = objSelecionado.get("title");
            }
        });            

        // Verifica se existe rede disponível:
        if (meusUtilitarios.haveInternet(this)) {
            ListaEventosTask asyncTask = new ListaEventosTask();
            asyncTask.execute();                
        }
        else {
            Toast.makeText(ListViewEventos.this, "Sem conexão à Internet", Toast.LENGTH_LONG).show();
            finish();
        }                       
    }
    private class ListaEventosTask extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... params) {
            xml = AuxXMLfunctions.getXML("http://kanegae.com.br/eventus/api/1.0/eventos.php");
            doc = AuxXMLfunctions.XMLfromString(xml);
            List<Map<String,?>> listaItens = new LinkedList<Map<String,?>>(); 
            NodeList nodes = doc.getElementsByTagName("evento");
            for (int i = 0; i < nodes.getLength(); i++) {    
                Element e = (Element)nodes.item(i);
                    listaItens.add(createItem(AuxXMLfunctions.getValue(e, "nome"),AuxXMLfunctions.getValue(e, "qtde_atividades") + " atividades programadas",AuxXMLfunctions.getValue(e, "codigo"),"0"));               
            }
            adapter.addSection("Selecione o evento", new SimpleAdapter(ListViewEventos.this, listaItens, R.layout.lista, new String[] {ITEM_TITLE, ITEM_CAPTION}, new int[] { R.id.list_complex_title, R.id.list_complex_caption}));
            return null;
        }       
        @Override 
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            list.setAdapter(adapter);       
            ListViewEventos.this.setContentView(list);          
        }       
    }   

目前您没有调用setContentView来设置当前活动的布局,然后从布局访问视图。

第二个问题,你需要用findViewById来初始化ListView实例,而不是创建一个调用默认构造函数的ListView类实例。

public class ListViewEventos extends ListActivity {
//...your code here...
AuxDAO myDAO;
AuxUtilitarios meusUtilitarios;
ListView list;
BaseAdapterListas adapter;
private ProgressDialog progressDialog;
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
// set Activity layout here
   myDAO= new AuxDAO(this);
   meusUtilitarios = new AuxUtilitarios(this);
   list =this.getListView();
   adapter= new BaseAdapterListas(this);
//....your code here...

已解析。但是,我不知道这是否是最好的方法。请看下面的代码:

public void onCreate(Bundle icicle) {super.onCreate(冰柱);

    myDAO           = new AuxDAO(this);
    meusUtilitarios = new AuxUtilitarios(this);     
    adapter         = new BaseAdapterListas(this);          
    list            = new ListView(this);
    list.setBackgroundColor(Color.WHITE);
    list.setCacheColorHint(Color.WHITE);
    list.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> a, View v, final int position, long id) {
            @SuppressWarnings("unchecked")
            HashMap<String, String> objSelecionado = (HashMap<String, String>) list.getItemAtPosition(position);
            // 1 - Sincroniza a programação do evento selecionado:
            importaProgramacao(objSelecionado.get("id"));
            // 2 - Armazena o código da Unidade e o seu nome para serem passados para o Menu Principal:
            codEvento  = objSelecionado.get("id");
            nomeEvento = objSelecionado.get("title");
        }
    });            

    // Verifica se existe rede disponível:
    if (meusUtilitarios.haveInternet(this)) {
        ListaEventosTask asyncTask = new ListaEventosTask();
        asyncTask.execute();                
    }
    else {
        Toast.makeText(ListViewEventos.this, "Sem conexão à Internet", Toast.LENGTH_LONG).show();
        finish();
    }                       
}
private class ListaEventosTask extends AsyncTask<Void, Void, Void> {
    @Override
    protected Void doInBackground(Void... params) {
        xml = AuxXMLfunctions.getXML("http://kanegae.com.br/eventus/api/1.0/eventos.php");
        doc = AuxXMLfunctions.XMLfromString(xml);
        List<Map<String,?>> listaItens = new LinkedList<Map<String,?>>(); 
        NodeList nodes = doc.getElementsByTagName("evento");
        for (int i = 0; i < nodes.getLength(); i++) {    
            Element e = (Element)nodes.item(i);
                listaItens.add(createItem(AuxXMLfunctions.getValue(e, "nome"),AuxXMLfunctions.getValue(e, "qtde_atividades") + " atividades programadas",AuxXMLfunctions.getValue(e, "codigo"),"0"));               
        }
        adapter.addSection("Selecione o evento", new SimpleAdapter(ListViewEventos.this, listaItens, R.layout.lista, new String[] {ITEM_TITLE, ITEM_CAPTION}, new int[] { R.id.list_complex_title, R.id.list_complex_caption}));
        return null;
    }       
    @Override 
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        list.setAdapter(adapter);       
        ListViewEventos.this.setContentView(list);          
    }       
}   

相关内容

  • 没有找到相关文章