android - Updating ListView from AsyncTask called from custom adapter class

此生再无相见时 提交于 2021-02-07 10:30:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!