【问题标题】:Pass ListView in AsyncTask在 AsyncTask 中传递 ListView
【发布时间】: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.javaMainActivity.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


【解决方案1】:

我认为你不能设置内容视图,它必须在 backgroundWorker 对象之前。或者检查您的主要活动中必须有一个列表视图。

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

【讨论】:

  • 哦,对不起,我在 BackgroundWorker 对象之后设置了内容视图,这就是为什么无法获取列表视图的原因。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-13
  • 1970-01-01
  • 2012-05-29
  • 2020-08-18
  • 1970-01-01
相关资源
最近更新 更多