In my previous post, I had explained how to switch (call) to another activities and passing value to it. This time I will try to explain on how to return some value back to the calling activity.
Returning some values to the calling activity can be done by the following example:
Intent resultData = new Intent();
String token = "some token";
String verifier = "some verifier";
resultData.putExtra("token", token);
resultData.putExtra("verifier", verifier);
setResult(Activity.RESULT_OK, resultData);
finish();
This is how it works:
- Create an intent that will hold your data.
- put extra data to the intent by calling putExtra() method to the intent
- call activity’s setResult() method and passing the resultCode and the intent.
- call finish() method to finish the activity and returning to the calling activity.
In calling activity, you need to override the onActivityResult method to catch the returned value from other activity. By assuming that you had previously called the returning value activity by the following example:
final int BROWSER_ACTIVATION_REQUEST = 2; // request code
startActivityForResult(someIntent, BROWSER_ACTIVATION_REQUEST);
requestCode is used to distinguish between different multiple activity calling when getting the activity results.
Then, to get the activity result, you need to simply override the onActivityResult method. For example:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the results is coming from BROWSER_ACTIVATION_REQUEST
if (requestCode == BROWSER_ACTIVATION_REQUEST) {
// check the result code set by the activity
if (resultCode == RESULT_OK) {
// get the intent extras and get the value returned
String token = data.getExtras().getString("token");
String verifier = data.getExtras().getString("verifier");
// do something with returned value
// Tip: check for the null value before you use the returned value,
// otherwise it will throw you a NullPointerException
}
}
}