[英]Android call notifyDataSetChanged from AsyncTask
我有一个自定义ListAdapter,它可以从AsyncTask中的Internet上获取数据。
数据完美地添加到了列表中,但是当我尝试执行操作时,应用程序崩溃了...
我确定这是因为我正在调用notifyDataSetChanged(); 在错误的时间(即AsyncTask结束之前)。
我现在所拥有的:
public class MyListAdapter extends BaseAdapter {
private ArrayList<String> mStrings = new ArrayList<String>();
public MyListAdapter() {
new RetreiveStringsTask().execute(internet_url);
//here I call the notify function ****************
this.notifyDataSetChanged();
}
class RetreiveStringsTask extends AsyncTask<String, Void, ArrayList<String>> {
private Exception exception;
@Override
protected ArrayList<String> doInBackground(String... urls) {
try {
URL url= new URL(urls[0]);
//return arraylist
return getStringsFromInternet(url);;
} catch (Exception e) {
this.exception = e;
Log.e("AsyncTask", exception.toString());
return null;
}
}
@Override
protected void onPostExecute(ArrayList<String> stringsArray) {
//add the tours from internet to the array
if(stringsArray != null) {
mStrings.addAll(toursArray);
}
}
}
}
我的问题是:我可以从AsyncTask的onPostExecute函数中调用notifyDataSetChanged()还是在AsyncTask提取数据后的其他任何时间调用?
我可以从AsyncTask中的onPostExecute函数调用notifyDataSetChanged()
是的,您可以在doInBackground
执行完成时从onPostExecute
调用notifyDataSetChanged()
来更新适配器数据。 这样做:
@Override
protected void onPostExecute(ArrayList<String> stringsArray) {
//add the tours from internet to the array
if(stringsArray != null) {
mStrings.addAll(toursArray);
// call notifyDataSetChanged() here...
MyListAdapter.this.notifyDataSetChanged();
}
}
调用notifyDataSetChanged()
中的onPostExecute()
为
@Override
protected void onPostExecute(ArrayList<String> stringsArray) {
//add the tours from internet to the array
if(stringsArray != null) {
mStrings.addAll(toursArray);
MyListAdapter.this.notifyDataSetChanged();
}
}
你尝试调用它在onPostExecute
的方法ASyncTask
。 onPreExecute
和onPostExecute
用于更新UI。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.