问题描述
我有一个自定义 ListAdapter,可以在 AsyncTask 中从 Internet 获取数据.
I've a custom ListAdapter that fetches data from internet in an AsyncTask.
数据已完美添加到列表中,但是当我尝试执行操作时应用程序崩溃...
The data is added perfectly to the list, but when I try to do operations the application crashes...
我确定这是因为我正在调用 notifyDataSetChanged();在错误的时间(即在 AsyncTask 结束之前).
I'm sure this is because I'm calling notifyDataSetChanged(); at the wrong time (i.e. before the AsyncTask ends).
我现在所拥有的:
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 获取数据后的任何其他时间调用?
My question is: can I call notifyDataSetChanged() from the onPostExecute function in the AsyncTask or at any other time when the AsyncTask has fetched the data?
推荐答案
我可以从 onPostExecute 函数调用 notifyDataSetChanged() 吗?异步任务
can I call notifyDataSetChanged() from the onPostExecute function in the AsyncTask
是的,您可以在 doInBackground
执行完成时从 onPostExecute
调用 notifyDataSetChanged()
来更新适配器数据.这样做:
Yes, you can call notifyDataSetChanged()
from onPostExecute
to Update Adapter data when doInBackground
execution complete. do it as:
@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();
}
}
这篇关于Android 从 AsyncTask 调用 notifyDataSetChanged的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!