Roland
Roland

Reputation: 876

How to know of what activity is returning

I have 3 activities: A, B and C.

From A I got to B and from A I go to C.

A --- B
|
|
C

When I return to A from this two activities, I press the back button.

From A, how can I know what activity was in the stack? How can I know if was B or C?

UPDATE - - I want to know how to know what activity press onBackPress(); I do not use startActivity from B or C;

Upvotes: 0

Views: 78

Answers (3)

Melquiades
Melquiades

Reputation: 8598

Just use Android's request codes with startActivityForResult(). In Activity A, call B or C with different request codes. First, define the codes:

private static final int ACTIVITY_B_REQUEST = 100;
private static final int ACTIVITY_C_REQUEST = 200;

Then start actvities.

B:

Intent intent = new Intent(this, ActivityB.class);
startActivityForResult(intent, ACTIVITY_B_REQUEST);

and C:

Intent intent = new Intent(this, ActivityC.class);
startActivityForResult(intent, ACTIVITY_C_REQUEST);

Then, still in your ActivityA, override onActivityResult() and check which request code has returned when back button was pressed:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {
        case ACTIVITY_B_REQUEST:
            //returned from ActivityB
            break;

        case ACTIVITY_C_REQUEST:
            //returned from ActivityC
            break;

        default:
            break;        
    }
}

No need to pass anything from B or C - it's already taken care of by Android.

Upvotes: 1

Yauraw Gadav
Yauraw Gadav

Reputation: 1746

Start Activity B & C as startActivityForResult, use setResult method for sending data back From B/C and in A receive data as onActivityResult.

How to pass data from 2nd activity to 1st activity when pressed back? - android

Upvotes: 1

Nathan Walters
Nathan Walters

Reputation: 4136

When starting activities A and C, use startActivityForResult(...) instead of the regular startActivity(...). You can create static integer variables for ACTIVITY_ID, ACTIVITY_B, and ACTIVITY_C. When your user backs out of either B or C, call setResult(...) with the corresponding ID variable. For more information about this method, see the developer doc on Activities: http://developer.android.com/reference/android/app/Activity.html

Upvotes: 2

Related Questions