【发布时间】:2017-02-21 07:21:26
【问题描述】:
我正在使用AsyncTask 从数据库中获取联系人。并想在listview 中展示它。但我面临一个问题。这是一个代码。
public class BackgroundWorker extends AsyncTask<String,Void,String> {
private Context context;
private ListView listView;
BackgroundWorker(Context ctx){
context = ctx;
}
BackgroundWorker(Context ctx, ListView lv){
context = ctx;
listView = lv;
}
// Other code
@Override
protected void onPostExecute(String result){
// convert result string in name and phone array and pass to contentAdapet
// Content adapter is extended from array adapter and used to display data in listview which is working fine.
ContentAdapter contentAdapter = new ContentAdapter(context, names, phones);
listView.setAdapter(contentAdapter);
}
// reset of code
}
MainActivity
ListView listView = (ListView) findViewById(R.id.listView);
BackgroundWorker backgroundWorker = new BackgroundWorker(this, listView);
backgroundWorker.execute("argument");
控制台错误
E/AndroidRuntime: FATAL EXCEPTION: main
Process: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
这两个类是不同的java文件,不在同一个文件中。 BackgroundWorker.java 和 MainActivity.java
【问题讨论】:
-
设置 listView 为 this.listView = lv;在你的构造函数中,看看它是否有效。
-
不,这不行,我试过了
-
你为什么要在AsyncTask中传递listView,只要在你的主类中声明,在onPostExecute()中使用就可以了。
-
对不起,如果我尝试在 onPostExecute() 中访问
findViewById,在 onPostExecute() 中使用它是什么意思,这不起作用。我是android新手,你能解释一下你到底在说什么吗? -
在 MainActivity 的 onCreate 之外声明您的 ListView,然后在 MainActivity 的 onCreate 中对其进行初始化,并在您的 AsyncTask 中使用它...目前您正在使用 AsyncTask 中的 listView...不要将 listView 作为参数传递在你的 AsyncTask 的构造函数中......
标签: android listview android-asynctask