Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

result not set in onPause() using setResult() when pressing the Back button

Tags:

android

I have 2 activities AAA and BBB. I call BBB from AAA using startActivityForResult(Intent, int). After I am done with BBB, I press the Back button to return to AAA. In BBB, I override onPause() and set the result by using setResult(RESULT_OK).

In AAA, I check my result in onActivityResult(int requestCode, int resultCode, Intent data) and I keep getting RESULT_CANCELLED.

After spending sometime on google/stackoverflow, I figured out that if I override onBackPressed() and set the result in it, then it works absolutely fine.

What I fail to understand is that, why is the result not getting set in onPause(), when in fact onPause() gets called after onBackPressed(). I have gone through the activity flows in the Dev docs and I am pretty clear about what has been mentioned there.

Anyone got any ideas about this behavior or could explain it better?

like image 638
Shubhayu Avatar asked Apr 05 '12 06:04

Shubhayu


2 Answers

You should take a look at the onActivityResult reference. http://developer.android.com/reference/android/app/Activity.html#onActivityResult%28int,%20int,%20android.content.Intent%29

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. The resultCode will be RESULT_CANCELED if the activity explicitly returned that, didn't return any result, or crashed during its operation.

You will receive this call immediately before onResume() when your activity is re-starting.

Call setResult in finish(). Besause onPause() can be called when a new activity is start from BBB.

like image 162
Shaiful Avatar answered Nov 11 '22 16:11

Shaiful


I think the issue here might be that onPaused might be called after you have already returned to the previous activity. I saw similar behaviour in other testing. Try adding some Log.d printouts to confirm the order of the onPause call versus the onActivityResult call.

like image 1
MikeIsrael Avatar answered Nov 11 '22 17:11

MikeIsrael