Alexander Ameye
Alexander Ameye

Reputation: 185

How to return data from activity2 to activity1 if I don't know when activity2 will end?

So I have activity 1, which is a main menu activity. Then I have activity 2 which is a store page. The store activity starts with the current user balance. When the user is in the store, he can purchase several things.

I want to send the updated balance back to the main menu activity after the user purchased things. I am using StartActivityForResult but the issue is that I don't know when activity 2 (the store) will end. I don't use a 'finish' button or anything that takes the user back to the main menu. The user just goes back to the main menu by clicking the back button on his phone.

How would I tackle this problem and send back the updated balance to activity 1?

Thank you in advance,

Alexander

Upvotes: 0

Views: 92

Answers (3)

Nitesh
Nitesh

Reputation: 3903

There are multiple ways to achieve this and you can use any.

1) You can override the onBackPress method of Activity2 to detect when the user is pressing the back button and set your result there.

2) You can fetch the updated balance from your database when your Activity1's onStart method get called. (Or you can use live-data/Data binding for single source of truth)

3) You can use a singleton class to maintain the current balance. Update it in Activity2 and fetch it in Activity1.

Upvotes: 1

David Wasser
David Wasser

Reputation: 95578

Activity1 should launch Activity2 using startActivityForResult().

Every time the user does something in Activity2, call setResult() with an Intent containing the current balance in an "extra".

When the user presses the BACK button, onActivityResult() will be called in Activity1 with the last Intent that you passed to setResult(). You can then extract the current balance from the "extra" in the `Intent.

You don't need to override anything.

Upvotes: 1

kAvEh
kAvEh

Reputation: 562

According to official doc

you can call second activity like this:

Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
pickContactIntent.setType(Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers
startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);

and then in your first activity waiting for result in this way:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Check which request we're responding to
    if (requestCode == PICK_CONTACT_REQUEST) {
        // Make sure the request was successful
        if (resultCode == RESULT_OK) {
            // The user picked a contact.
            // The Intent's data Uri identifies which contact was selected.

            // Do something with the contact here (bigger example below)
        }
    }
}

Upvotes: 0

Related Questions