Android: Returning Value To The Calling Activity

android_icon_256In 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);

This is how it works:

  1. Create an intent that will hold your data.
  2. put extra data to the intent by calling putExtra() method to the intent
  3. call activity’s setResult() method and passing the resultCode and the intent.
  4. 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:

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

42 Replies to “Android: Returning Value To The Calling Activity”

  1. Your article reflects the issues people care about. The article provides timely information that reflects multi-dimensional views from multiple perspectives. I look forward to reading quality articles containing timely information from you. Thank you for sharing this great information.

  2. Giá phế liệu inox 304 36.500 – 71.900đ/kg
    Giá phế liệu inox 201 20.000 – 40.700đ/kg
    Giá phế liệu inox 430, 410, 409 15.500 – 37.000đ/kg
    Giá phế liệu inox 510 12.000đ – 16.10đ/kg
    Giá phế liệu inox 630 50.100 – 95.100đ/kg
    Giá phế liệu inox 205, 253 10.100 – 20.200đ/kg
    Giá inox vụn, ba dớ inox 10.200 – 12.200đ/kg

Leave a Reply

Your email address will not be published. Required fields are marked *