Kishore
Kishore

Reputation: 2051

How to update current activity from async task

I have listview in one screen and I will render this listview using customized arraylist(List).here when I want to refresh the listview from another java class I will refersh listview with context.But there is nomeaning if I will just refersh the listview ,I have to change the arraylist also.For this how can I change arraylist from another java class without using static modifier.

Upvotes: 0

Views: 1155

Answers (2)

10s
10s

Reputation: 1699

try this:

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

As mentioned by @Venkata Krishna comment below if you want to just update a property your code should like this:

...
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();
    }
}

Just java programming with global and inner class variables. For regular object you don't need to have the "context" of the activity. Just change the variables, if you want to access the UI you would need to do the trick with storing the context property.

Upvotes: 1

user370305
user370305

Reputation: 109237

Using the reference (context) of that activity update UI elements on onPostExecute() of AsyncTask.

Upvotes: 1

Related Questions