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
基础教程推荐
- 将 double 转换为 Int,向下舍入 2022-01-01
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
- 将 Windows 证书导入 Java 2022-01-01
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
- JPA惰性列表上的流 2022-01-01
- Maven:无效的目标版本:10 2022-01-01
- 在springboot中如何给mybatis加拦截器 2023-04-29
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
