Set Custom Activity Result on Back Button Click
The android Activity documentation for setResult() states: “to set the result that your activity will return to its caller.” So why does setResult(MyActivity.MY_RETURN_VALUE) not return your custom value to the calling activity’s onActivityResult() event? To return a value other than RESULT_CANCELED you need to override the finish method and set your return value there.
@Override
public void finish() {
if (userChangedSomething){
setResult(MyActivity.MY_RETURN_VALUE);
}
super.finish();
}
Should the Back button really return a CANCELED value – probably not. Many would argue the Back button is for navigation and its return value should not be used to infer the user’s acceptance of state changes in the child activity.
Another way to return a custom value to the onActivityResult() event is to add a button (or other event listener) in the child activity and in an event listener call setResult() and then call finish();