Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - How to send data back to the calling activity

I am calling activityB from activityA and passing a class object using intent.

Intent intentB = new Intent(v.getContext(), activityB.class);
intentB.putExtra("data", data); //data is a class object
startActivity(intentB);

The activityB starts fine and also I am able to extract data. In activityB, I am modifying the data object. I want to send this modified data object back to activityA when activityB.onDestroy() is called.

Any advice?

Here is my code:

activityA, starting the Intent:

Intent i = new Intent(this, activityB.class);
i.putExtra("object", Class.object);
startActivityForResult(i, 1);

activityA, catching the intent:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (requestCode == 1) {    
        object = data.getParcelableExtra("object"); //the Class implements Parcelable
  }
}

activityB

protected void onDestroy() {
  Intent data = new Intent();
  setResult(RESULT_OK, data) 
  finish(); // ends current activity
}
like image 766
anirus Avatar asked Mar 10 '13 19:03

anirus


1 Answers

Make use of the ActivityResult.

  1. Use startActivityForResult(int, Intent)
  2. To set information in Activity B, use setResult(RESULT_OK, data) (where data is an Intent)
  3. Override onActivityResult(int, int, Intent) and catch the data-Intent

Activity A, starting the Intent:

Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, 1);

Activity A, catching the data:

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

  if (requestCode == 1) {    
        // make use of "data" = profit
  }
}

Activity B:

Intent data = new Intent();
setResult(RESULT_OK, data) 
finish(); // ends current activity
like image 109
poitroae Avatar answered Sep 26 '22 15:09

poitroae