【发布时间】:2012-07-10 05:30:43
【问题描述】:
我遇到了以下问题,希望有人能给我提示。
我有一个执行AsyncTask< String, Void, ArrayList<Custom object >> 的活动。
在doInBackground() 函数中,我设置了一个新的自定义对象ArrayList,它也是返回值。
在onPostExecute() 方法中,ArrayList 用于新创建的ArrayAdapter<Custom object>,它也设置为ListView 和lv.setAdapter(adapter).
到目前为止一切顺利!
现在的事情是:回到 MainActivity 我将再次需要那个适配器,因为我想通过调用 adapter.add(items). 向它添加新项目
现在,我将 AsyncTask 作为 MainActivity 的内部类,并且可以使用同样的 ListView 和同样的 ArrayAdapter,,效果非常好!
但是因为我还有另一个类也需要执行 AsyncTask,所以我将内部类 AsyncTask 更改为独立的 .java 文件 (CustomAsyncTask.java)
-> 现在,当我尝试向 ArrayAdapter 添加新项目时,它会抛出 NullPointerException!
当然就是,因为ArrayAdapter 属于AsyncTask 并在那里创建
所以我尝试将 MainActivity 中的 ListView 和 ArrayAdapter 作为 CustomAsyncTask 构造函数的参数,以便在其中使用它
但这不起作用,MainActivity 中的 ArrayAdapter 始终为 null 导致异常
任何想法如何解决? 我真的很感激。
这里是MainActivity.java的代码:
// global variables
ArrayAdapter<Custom object> arrayadapter;
ListView listview;
ProgressBar progressbar;
...
protected void myMethod() {
CustomAsyncTask hTask = new CustomAsyncTask(this, listview, progressbar, arrayadapter);
hTaskPlaylist.execute(String sth);
}
...
protected void anotherMethod() {
arrayadapter.add(item);
}
以及CustomAsyncTask.java的代码:
package com.mypackage.test;
import java.util.ArrayList;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
public class CustomAsyncTask extends AsyncTask<String, Void, ArrayList<Custom object>>{
Context context;
ListView listview;
ProgressBar progressbar;
ArrayAdapter<Custom object> arrayadapter;
public CustomAsyncTask(Context con, ListView lv, ProgressBar pb, ArrayAdapter<Custom object> aa) {
this.context = con;
this.listview = lv;
this.progressbar = pb;
this.arrayadapter = aa;
}
@Override
protected void onPreExecute() {
listview.setVisibility(ListView.GONE);
progressbar.setVisibility(ProgressBar.VISIBLE);
super.onPreExecute();
}
@Override
protected ArrayList<Custom object> doInBackground(String... params) {
ArrayList<Custom object> list = new ArrayList<Custom object>();
... doing something and populating list
return list;
}
@Override
protected void onPostExecute(ArrayList<Custom object> list) {
super.onPostExecute(list);
arrayadapter = new ArrayAdapter<Custom object>(context, android.R.layout.simple_list_item_1, list);
listview.setAdapter(arrayadapter);
progressbar.setVisibility(ProgressBar.GONE);
listview.setVisibility(ListView.VISIBLE);
}
}
}
【问题讨论】:
标签: android arraylist android-asynctask return-value android-arrayadapter