Home » Android » android – Do I need to explicitly setResult to RESULT_CANCELED?

android – Do I need to explicitly setResult to RESULT_CANCELED?

Posted by: admin June 15, 2020 Leave a comment


I have an activity that expects the user to select an item, but the user can instead choose to click the back button without selecting an item. This “item selecting” activity is started with startActivityForResult().

I was wondering two things. First, is it sufficient to only setResult(RESULT_OK) when the item is actually selected, i.e., can I rely upon the result not being set to RESULT_OK if I don’t set it explicitly?

Second, if this isn’t sufficient to rely upon the (uninitialized) result, is it okay to call setResult() multiple times, the first time “initializing” the result to RESULT_CANCELED, and then calling SetResult(RESULT_OK) after the user selects an item and before finishing the activity?

How to&Answers:

From the documentation:

If a child activity fails for any reason (such as crashing), the
parent activity will receive a result with the code

So the result is already RESULT_CANCELED, if
you don’t explicitly specify the other code. When the user exits your
app via “back” button – you receive RESULT_CANCELED as well.


You can use setResult(RESULT_CANCELED) on each Activity and call finish().

In the overrided OnActivityResult, do as I have mentioned if the result code is canceled.