[英]android - Updating ListView from AsyncTask called from custom adapter class
I am trying to update a ListView from an AsyncTask. 我正在尝试从AsyncTask更新ListView。 I have this situation:
我有这种情况:
How can I call notifyDataSetChanged from onPostExecute() method in the Utilities AsyncTask? 如何在实用程序AsyncTask中的onPostExecute()方法中调用notifyDataSetChanged?
Include a Delegate as a callback to activate the refresh from within the original class. 包括一个委托作为回调,以从原始类中激活刷新。
For example, add this interface: 例如,添加以下接口:
public interface AsyncDelegate {
public void asyncComplete(boolean success);
}
Then, in your calling class, implement the interface, and pass it to your task 然后,在您的调用类中,实现接口,并将其传递给您的任务
public class MyClass implements AsyncDelegate {
// Class stuff
MyAsyncTask newTask = new MyAsyncTask(this);
newTask.execute();
public void asyncComplete(boolean success){
myAdapter.notifyDataSetChanged();
}
In the AsyncTask, return the result: 在AsyncTask中,返回结果:
private class MyAsyncTask extends AsyncTask<Object, Object, Object> {
private AsyncDelegate delegate;
public MyAsyncTask (AsyncDelegate delegate){
this.delegate = delegate;
}
@Override
protected void onPostExecute(String result) {
delegate.asyncComplete(true);
}
}
When the task completes, it will call the delegate, which will trigger the refresh! 任务完成后,它将调用委托,这将触发刷新!
Here is an example: 这是一个例子:
newslist is a ArrayList. 新闻列表是一个ArrayList。 nAdapter is a generic adapter.
nAdapter是通用适配器。
So first you clear your list, then add all your new content. 因此,首先您要清除列表,然后添加所有新内容。 After, you says to your Adapter that your content have been changed.
之后,您对适配器说您的内容已更改。
@Override
protected void onPostExecute(ArrayList<HashMap<String, String>> list) {
newsList.clear();
newsList.addAll(list);
nAdapter.notifyDataSetChanged();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.