Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value for resultCode when activity finishes

This might be a basic question, but I hoping to get some clarity.

What I am trying to do: 1) Starting an activity with a requestCode, and handling two operations in onActivityResult, one using RESULT_OK, another using RESULT_CANCELLED. I explicitly state each of them.

The issue is even when I close the activity just using back button and not setting any result the Activity in the back stack receives RESULT_CANCELLED.

Going through the source code I see that RESULT_CANCELLED is the default value for the resultcode and that the resultcode is always sent back.

enter image description here

enter image description here

Am i reading this right and is this what happens all the time? or am I doing something wrong in my application?

Source: https://github.com/android/platform_frameworks_base/blob/master/core/java/android/app/Activity.java

like image 797
Nitesh Mudireddy Avatar asked Nov 21 '15 02:11

Nitesh Mudireddy


2 Answers

When your starting Activity is restarting, the onActivityResult(..) method of this Activity is called before the onResume() method is called. check Doc for Activity

And the default resultCode is RESULT_CANCELLED.

You must explicitly call setResult(int) in the started Activity to change the value of resultCode.

And that's why it's important to check resultCode == RESULT_OK in the onActivityResult method. Because the onActivityResult can be called even if you have not called startActivityForResult.

Which can be confusing, but that's the default behaviour.

  @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Check which request we're responding to
    if (requestCode == YOUR_REQUEST) {
        // Make sure the request was successful
        if (resultCode == RESULT_OK) {
            // so some work
        }
    }
}
like image 131
Eric Liu Avatar answered Sep 24 '22 01:09

Eric Liu


You must always supply a result code by help of setResult() method

like image 24
Varun Kumar Avatar answered Sep 27 '22 01:09

Varun Kumar