setResult does not work when BACK button pressed
I am trying to setResult after the BACK button was pressed. I call in onDestroy
Intent data = new Intent();
setResult(RESULT_OK, data)
But when it comes to
onActivityResult(int requestCode, int resultCode, Intent data)
the resultCode is 0 (RESULT_CANCELED) and data is 'null'.
So, how can I pass result from activity terminated by BACK button?
You need to overide the onBackPressed()
method and set the result before the call to superclass, i.e
@Override
public void onBackPressed() {
Bundle bundle = new Bundle();
bundle.putString(FIELD_A, mA.getText().toString());
Intent mIntent = new Intent();
mIntent.putExtras(bundle);
setResult(RESULT_OK, mIntent);
super.onBackPressed();
}
Activity
result must be set before finish()
is called. Clicking BACK actually calls finish()
on your activity
, so you can use the following snippet:
@Override
public void finish() {
Intent data = new Intent();
setResult(RESULT_OK, data);
super.finish();
}
If you call NavUtils.navigateUpFromSameTask();
in onOptionsItemSelected()
, finish()
is called, but you will get the wrong result code
. So you have to call finish()
not navigateUpFromSameTask
in onOptionsItemSelected()
.
wrong requestCode in onActivityResult
If you want to set some custom RESULT_CODE
in onBackPressed
event then you need to first set the result
and then call the super.onBackPressed()
and you will receive the same RESULT_CODE
in the caller activity's onActivityResult
method
@Override
public void onBackPressed()
{
setResult(SOME_INTEGER);
super.onBackPressed();
}
I refactored my code. Initially I prepared some data and set it as activity result
in onDestroy
(this did not work). Now I set activity
data each time the data to be returned is updated, and have nothing in onDestroy
.