Domanda

I have an ArrayAdapter and within it an AsyncTask but I'm not sure how to call notifyDataSetChanged from the onPostExecute

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 the above from my activity like this:

  adapter = new ColorAdapter(context, colorsList);
  setListAdapter(adapter);
È stato utile?

Soluzione

You can call it like this:

ColorAdapter.this.notifyDataSetChanged();

As an aside, a more appropriate place to launch this AsyncTask would be from it's host fragment/activity, why? AsyncTasks sometimes tend to stick around longer than you expect, if you don't manage their lifecycle appropriately they can cause trouble.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top