Activity 1
Create a class variable for reference.
private final int REQUEST_CODE = 0;
...
//Somewhere in your code you have to call startActivityForResult
Intent intent = new Intent(Activity1.this, Activity2.class);
startActivityForResult(intent);
Activity 2
Before ending Activity2 you have to set the result to OK and place the data that you want to bring back to Activity1 likeso
Intent data = new Intent();
data.putExtra("name", "Mark");
data.putExtra("number", 1);
data.putExtra("areYouHappy", true);
setResult(RESULT_OK, data);
finish(); //closes Activity2 and goes back to Activity1
Now go back to Activity1, you should override onActivityResult method and RETRIEVE the values from Activity2.
You do this by first checking if Activity2's result is OK, then check the reference REQUEST_CODE you passed. Since earlier we created private final int REQUEST_CODE = 0
then we check if requestCode is equal to the variable REQUEST_CODE. If it is then extract the data from Activity 2.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==RESULT_OK) {
if(requestCode==REQUEST_CODE) {
if(data.getExtras()!=null) {
String name = data.getStringExtra("name");
int number = data.getIntExtra("number",0); //2nd parameter is the default value in case "number" does not exist
boolean areYouHappy = data.getBooleanExtra("areYouHappy", false); //2nd parameter is the default value in case "areYouHappy" does not exist
}
}
}
}