Android- Going back to Previous Activity with different Intent value

What you want is startActivityForResult(). When you go from C to D, instead of using startActivity() use instead startActivityForResult(). Then when you want to return from D to C you use setResult() which can include an Intent object with extras to pass back to C.

I don’t recommend doing this in onBackPressed() if you don’t have to because this will not be what the user expects. Instead, you should return with this data with an event such as a Button click.

So, in C you will do something like

 Intent i = new Intent(new Intent(C.this, D.class);
 startActivityForResult(i, 0);

then in D when you are ready to return

 Intent i = new Intent();
 i.putExtra();  // insert your extras here
 setResult(0, i);

then when you return to C you will enter this method (taken from the Docs)

protected void onActivityResult(int requestCode, int resultCode,
         Intent data) {
     if (requestCode == PICK_CONTACT_REQUEST) {
         if (resultCode == RESULT_OK) {
             // A contact was picked.  Here we will just display it
             // to the user.
             startActivity(new Intent(Intent.ACTION_VIEW, data));

             /* 
                can also get the extra sent back through data
                using data.getStringExtra("someKey"); 
                assuming the extra was a String
             */

         }

Leave a Comment