How to call notifyDataSetChanged () from AsyncTask

I have ArrayAdapterinside it AsyncTask, but I'm not sure how to call notifyDataSetChangedfromonPostExecute

Example:

public class ColorAdapter extends ArrayAdapter<Color> {

  List<Color> colorList;
  Context context;
  ....

  public ColorAdapter(Context context, List<Color> list) {
    this.context = context; this.colorList = list;  
  }

  public View getView (final int position, final View view, final ViewGroup parent) { 
   .....
  }

  class DeleteColorTask extends AsyncTask <String, String, String> {
   int colorId;
   DeleteColorTask (int colorId) {this.colorId = colorId;} 

   protected String doInBackgroud (String ... args) {
     //call to server to delete the color
     colorList.remove(colorList.indexOf(...));
   }
   protected void onPostExecute(String s) {
     //HOW CAN I CALL notifyDataSetChanged() here?? this.notifyDataSetChanged() doesn't work since I am inside DeleteColorTask class
   }
  }
}

I call this from my activity as follows:

  adapter = new ColorAdapter(context, colorsList);
  setListAdapter(adapter);
+3
source share
1 answer

You can call it like this:

ColorAdapter.this.notifyDataSetChanged();

As an aside, a more suitable place to run this AsyncTaskwould be from it host fragment / activity, why? AsyncTasks sometimes tend to stick for longer than you expect, if you can't handle your life cycle, they can cause problems.

+4
source

All Articles