Android 在异步任务中传递ListView

Android 在异步任务中传递ListView,android,listview,android-asynctask,Android,Listview,Android Asynctask,我正在使用AsyncTask从数据库获取联系人。并希望在列表视图中显示它。但我面临一个问题。这是一个代码 public class BackgroundWorker extends AsyncTask<String,Void,String> { private Context context; private ListView listView; BackgroundWorker(Context ctx){ context = ctx;

我正在使用
AsyncTask
从数据库获取联系人。并希望在
列表视图中显示它。但我面临一个问题。这是一个代码

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
}
控制台错误

 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

我认为您不能设置内容视图,它必须在BackgroundWorker对象之前。或者检查主活动中必须有listview

   setContentView(R.layout.activity_main);
    ListView listView = (ListView) findViewById(R.id.listView);
        BackgroundWorker backgroundWorker = new BackgroundWorker(this, listView);
        backgroundWorker.execute("argument");

将listView设置为this.listView=lv;不,这不起作用,我试过了为什么要在AsyncTask中传递listView,只需在主类中声明它并在onPostExecute()中使用它。对不起,如果我试图在onPostExecute()中访问
findViewById
,那么在onPostExecute()中使用它是什么意思。我是android新手,你能解释一下你到底在说什么吗。在onCreate of MainActivity外部声明你的ListView,然后在onCreate of MainActivity中初始化它,并在AsyncTask中使用它…目前你在AsyncTask中使用ListView…不要在AsyncTask的构造函数中将ListView作为参数传递…哦,很抱歉,我将内容视图设置在BackgroundWorker对象之后,这就是您无法获取listview的原因。谢谢
   setContentView(R.layout.activity_main);
    ListView listView = (ListView) findViewById(R.id.listView);
        BackgroundWorker backgroundWorker = new BackgroundWorker(this, listView);
        backgroundWorker.execute("argument");