Tuesday 14 July 2009

Returning data from an Android Activity called from startActivityWithResult

I spent hours scratching my head in various disguises, until I finally found this email thread. Basically, the results set in the Activity.setResult() method is fixed and transmitted back to the calling Activity when the child Activity's finish() method is called. Using setResult in onPause is too late .. the child activity will already be going through a finish action (e.g. on a Back button press). What happens is that the parent Acticvity onActivityResult gets a callback with ResultCode? = 0 (RESULT_CANCELLED) and the intent data is always null. Argh!

The answer is to override the child Activity's finish() method, to ensure that the setResult is called before the super.finish() method is called.

@Override
public void finish() {

if (doSaveOnPause()) {
if (save()) {
// Set the insert / edit action result to OK
mSuccessfullySaved = true;

}
}

if(mSuccessfullySaved) {
// Notify the caller Activity that the user successfully
// edited or inserted the data set
Intent _intent = new Intent("inline-data").setData(mUri);

Log.d(TAG,"Completing, with result="+RESULT_OK+", data="+_intent.getData().toString());

setResult(RESULT_OK,_intent);
}
else {
// Notify the caller Activity that the user has canceled the activity
// without altering anything
Log.d(TAG,"Completing, with result="+RESULT_CANCELED);
setResult(Activity.RESULT_CANCELED);
}
// Prevent onPause to re-save the record again during the close down of the activity.
mSuccessfullySaved = false;

super.finish();


}

No comments:

Post a Comment