setResult does not work when BACK button pressed

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();
    }

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


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();
}

Tags:

Android