Handle data from several activities in one onActivityResult()?
Asked Answered
T

2

6

I wonder if it's possible to handle data from e.g. activity 2 and activity 3 in activity 1 that have one onActivityResult(), or do I need to have one method for each activity that return data?

Activity 1 is the main activity for the application.

Activity 1:

// Handle return value from activity
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK) {
        String imageId = data.getExtras().getString("imageId");

        // Do something if data return from activity 2 ??

        // Do something if data return from activity 3 ??
    }
}

Activity 2

Intent intent = new Intent();
intent.putExtra("imageId", imagePath);
setResult(RESULT_OK, intent); 
finish();

Activity 3

Intent intent = new Intent();
intent.putExtra("contactId", data);
setResult(RESULT_OK, intent);
finish();
Tomchay answered 21/2, 2013 at 12:0 Comment(1)
that's what requestCode is for.Characteristic
J
8

set requestCode in your startActivityForResult for activity 1:

calling activity 2

Intent intent = new Intent(this, Activity2.class);
startActivityForResult(intent,10); 

calling activity 3

Intent intent = new Intent(this, Activity3.class);
startActivityForResult(intent,11); 

Now when you come to onActivityResult check that requestCode

like:

 public void onActivityResult(int requestCode, int resultCode, Intent data)
 {

      super.onActivityResult(requestCode, resultCode, data);

       switch (requestCode) {

          case (10): 
          {
            // do this if request code is 10.
          }
          break;

          case (11):
          {
            // do this if request code is 11.
          }
          break;
  }
Jasik answered 21/2, 2013 at 12:8 Comment(3)
Is super.onActivityResult(requestCode, resultCode, data); necessary?Tomchay
Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.Jasik
In general (not specifically in Android stuff), when you derive, you should call through to the superclass's methods unless you know you shouldn't. It's a decision that needs to be case-by-case, but the default (I'd say) would be that you do it.Jasik
A
7

No confusion check result code and request code..

Example :

private static final int TWO = 2;
private static final int THREE = 3;

startActivityForResult(new Intent(this,Activity2.class),TWO); // one for Activity 2
startActivityForResult(new Intent(this,Activity3.class),THREE);

and

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK ) {
        if(requestCode == TWO) {
            // Activity two stuff
        } else if(requestCode == THREE) {
            // Activity three stuff
        }
    }
}
Argolis answered 21/2, 2013 at 12:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.