如何从AsyncTask中调用notifyDataSetChanged()

时间:2014-02-21 22:38:44

标签: java android android-asynctask android-adapter

我有一个ArrayAdapter,其中有AsyncTask,但我不确定如何从notifyDataSetChanged

致电onPostExecute

示例:

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
   }
  }
}

我从我的活动中称呼上述内容:

  adapter = new ColorAdapter(context, colorsList);
  setListAdapter(adapter);

1 个答案:

答案 0 :(得分:4)

您可以这样称呼它:

ColorAdapter.this.notifyDataSetChanged();

顺便说一下,启动这个AsyncTask的更合适的地方是来自它的主机片段/活动,为什么? AsyncTasks有时会比你预期的更长时间,如果你不适当地管理他们的生命周期,他们可能会带来麻烦。