C Smith
C Smith

Reputation: 808

Run code upon completion of Activity intent

I am relatively new to Android, so this has been boggling my mind. I currently have an activity which opens a second activity; the second activity allows you to select from a collection of strings and, upon clicking one, the activity closes.

The activity is called like this:

    final Intent intent = new Intent(context, theActivity.class);
    context.startActivity(intent);

What I want to be able to do is run code when that Activity is closed. In particular, I'm trying to reload some data upon the activity closing. An example of the flow would be

    final Intent intent = new Intent(context, theActivity.class);
    context.startActivity(intent);
    DoStuffLikeReloadingData(foo bar);

The problem, of course, is that DoStuffLikeReloadingData immediately runs after starting the activity, regardless of whether it is finished or not.

So what I was wondering: is there some sort of event I can hook into that will fire when the activity closes, so I can do what I want there? If not, can you guys think of a way in which I could monitor the activity and fire off code when it closes or completes, if it is called in this manner?

Any help would be great! Thank you.

Upvotes: 1

Views: 1642

Answers (2)

Cruceo
Cruceo

Reputation: 6824

Yes, you can start an Activity with the intention of asking for a result using the method startActivityForResult(Intent, int requestCode); which will then cause the Activity's onActivityResult(int requestCode, int resultCode, Intent data) method to be called when the called Activity returns.

Here's an example:

public static final int REQUEST_CODE_SOMETHING = 1001;

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
    if(requestCode == REQUEST_CODE_SOMETHING){
        // It came from our call
        if(resultCode == Activity.RESULT_OK){
            // The result was successful
            DoStuffLikeReloadingData(); // you can use the data returned by the Intent do figure out what to do
        }
    }
}

private void startActivity(){
    final Intent intent = new Intent(context, theActivity.class);
    startActivityForResult(intent, REQUEST_CODE_SOMETHING);
}

Now you can open an Activity and perform an operation on the result. If you want to pass data to, or back from, the Activity, you can do so by adding extras to the Intent via intent.putExtra(String key, Parcellable object).

In the second Activity, you should call the method setResult(int resultCode, Intent data) before calling finish() to pass the data back.

Upvotes: 2

hfann
hfann

Reputation: 599

Start your activity using startActivityForResult(). Then, in your activity's onActivityResult() method, call your DoStuffLikeReloadingData(foo bar);

Upvotes: 0

Related Questions