Android call notifyDataSetChanged from AsyncTask(Android 从 AsyncTask 调用 notifyDataSetChanged)
问题描述
我有一个自定义 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Android 从 AsyncTask 调用 notifyDataSetChanged
基础教程推荐
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 降序排序:Java Map 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01