简体   繁体   中英

onActivityResult Android

I am new to android and have the following query.

I am building an app, which contains 2 activities first and second which send messages to each other. 'first' sends a message to 'second' and then 'second' starts, displays the message received and sends back a message to 'first'. Finally first displays the message received.

In the first activity i have to start the second activity using startActivityForResult since i need a response back.

Question - when overriding onActivityResult why do we have to check if(resultCode == RESULT_OK)

According to the android website -

onActivityResult is "Called when an activity you launched exits, giving you the requestCode you started it with, the resultCode it returned, and any additional data from it. "

So if i have the set the ResultCode to Result_OK in 'second activity', why do i have to check resultCode in 'first' activity. ? Isnt onActivityResult called when the 'second' sets the resultCode and exits ?

Thanks !

PS - i have tried removing the statement - if(resultCode == RESULT_OK) . I get a NullPointerException.

Your activity may exits in two ways, first which sounds "normal" which you entered your message and maybe press some "done" button to finish it. This way you're setting the result to OK.

There's second way which user may press on back button, so your activity ends without capturing user input, thus your onActivityResult may get nothing. This way you get your null pointer exception, where you know user exited the activity 2 without entering proper input.

Hope you see why ResultCode is important in this case.

when you are in the second activity and you press the back key the second activity will be finished and the result code will not be 'OK'. So ResultCode is needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM