问题
I am trying to update a ListView from an AsyncTask. I have this situation:
- Activity Class creates the list adapter from a custom Adapter class.
- Adapter class sets onClickListener on element from list item, and calls an AsyncTask located in a different Utilities class.
How can I call notifyDataSetChanged from onPostExecute() method in the Utilities AsyncTask?
回答1:
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:
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!
回答2:
Here is an example:
newslist is a ArrayList. nAdapter is a generic adapter.
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();
}
来源:https://stackoverflow.com/questions/15693086/android-updating-listview-from-asynctask-called-from-custom-adapter-class