Jacob Malachowski
Jacob Malachowski

Reputation: 981

Pass back a value from an Activity when the calling activity finishes

I have Activity A, B, and C. Both Activity A and B have an option in the OptionsMenu to call activity C. However, if the user calls activity C from activity B I want them to return to activity A when activity C finishes. I can just use finish() after I call the activity from activity B, but how would I pass back a value to activity A if the intent was called from activity B?

To recap, I want to:

User is in activity B -> Calls activity C -> User returns to activity A, which receives a value from activity C.

Upvotes: 0

Views: 93

Answers (2)

Aniket Thakur
Aniket Thakur

Reputation: 69025

You can use method startActivityForResult() to start activity C

static private final int GET_TEXT_REQUEST_CODE = 1;
Intent intent = new Intent(this, C.class);
startActivityForResult(intent,GET_TEXT_REQUEST_CODE);

and then override onActivityResult() method

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Log.i("B", "Entered onActivityResult()");

    if(resultCode == Activity.RESULT_OK && requestCode == GET_TEXT_REQUEST_CODE){
        myTextView.setText(data.getStringExtra("MY_VALUE"));
    } 
} 

to get back the data. (Docs)

In activity C you need to set data like -

Intent intent  = new Intent();
intent.putExtra("MY_VALUE",input );
setResult(Activity.RESULT_OK, intent);

Upvotes: 0

Dhrumil Shah - dhuma1981
Dhrumil Shah - dhuma1981

Reputation: 15799

Call Activity A from Activity C and finish Activity C. To send data to Activity A use intent.putExtra();

Intent i=new Intent(ActivityC.this,ActivityA.class);
i.putExtra("Key","value you want to pass to activity A");
startActivity(i);
finish();

Upvotes: 1

Related Questions