Bachask8
Bachask8

Reputation: 428

Update Activity 1 from Activity 2's Asynk task

I have 2 activities, first one has a ListView that I want to update from second activitys async task.
How can accomplish this? I searched Google for a days but didn't find anything.

public class Activity1 extends Activity {
    ...
    //launch activity2
    }

In the second Activity some process is done and then i want to update Activity1:

public class Activity2 extends Activity {
    ...
    new UpdateDB ().execute();
    // Return to Activity 1 but UpdateDB is still working ..
    // ..after finished the work i want to update activity1
    setResult(RESULT_OK, null);
    finish();

    private class UpdateDB extends AsyncTask<Void, Void, Void> {
        ...
        protected void onPostExecute(Void unused) {
            // HERE TRYING TO UPDATE activity1
        }
    }
}

Upvotes: 0

Views: 129

Answers (3)

Subramanian Ramsundaram
Subramanian Ramsundaram

Reputation: 1347

You can use AsyncTask in second Activity. Do your effort in doInBackground and then call/update First Activity in onpostexecute

Upvotes: 0

codeMagic
codeMagic

Reputation: 44571

Put your code in onPostExecute()

    protected void onPostExecute(Void unused) {
    //HERE TRYING TO UPDATE activity1
     setResult(RESULT_OK, null);
     finish();
    }
  }

If you need to send some data back then use an Intent instead of null. Something like

 protected void onPostExecute(Void unused) {
    //HERE TRYING TO UPDATE activity1
     Intent i = new Intent();
     // add extras to send back
     setResult(RESULT_OK, i);   // pass back your Intent
     finish();
    }
  }

Then in Activity1 you have onActivityResult() which receives the Intent that you passed back in setResult(). I am assuming you are starting Activity2 with startActivityForResult().

Upvotes: 3

rekire
rekire

Reputation: 47945

You can store the changes in a SharedPreference. So you can access it on onResume of your first activity.

If the value is changed after the onResume callback use the OnSharedPreferenceChangeListener interface for being notified for changes.

Upvotes: 0

Related Questions