如何从异步任务更新当前活动

时间:2012-07-04 06:50:10

标签: android android-asynctask

我在一个屏幕上有listview,我将使用自定义的arraylist(List)来渲染这个listview。当我想从另一个java类刷新listview时,我将使用context来引用listview。但是如果我只是引用那么就会出现nomeaning在listview中,我也必须更改arraylist。为此,如何在不使用static修饰符的情况下从另一个java类更改arraylist。

2 个答案:

答案 0 :(得分:1)

使用该活动的引用(上下文)更新AsyncTask的onPostExecute()上的UI元素。

答案 1 :(得分:1)

试试这个:

...
private Activity context;

onCreate() {
   ...
   context = this;
   ...
   //run async task somewhere
}

class extends AsyncTask<> {

   onPostExecute() {
      AlertDialog alert = new AlertDialog(context);
      // every time you used this on the activity you should use context on any other classes, including async task or other non activity classes
}

正如@Venkata Krishna所提到的,如果你想更新你的代码应该喜欢的属性,请注意以下内容:

...
private ArrayList<String> values;
private Activity context;

onCreate() {
    ...
    context = this;
    ...
    //run async task somewhere
}

class extends AsyncTask<> {
    private ArrayList<String> values;

    onPostExecute() {
        AlertDialog alert = new AlertDialog(context);
        //notice that there are 2 properties of values with the same name and the same signature
        //accessing async task's values
        this.values = ...;
        //accessing global parameter
        values = ...;
        // and then he would want to access the list adapter to update the infomation
        CustomListAdapter adapter = ((ListView)findViewById(R.id.listview)).getListAdapter();
        adapter.notifyDatasetChanged();
    }
}

使用全局和内部类变量进行java编程。对于常规对象,您不需要具有活动的“上下文”。只需更改变量,如果要访问UI,则需要存储上下文属性。