Get the Result From Last Activity When Middle Activity Is Finished
We usually get the result from an activity by starting it with
startActivityForResult()
and listening to the onActivityResult()
in the calling activity. But there are some cases, where we may want the result to be received from the subsequent activities rather than the immediately invoked activity.
For example, let's take three activities named
FirstActivity
, SecondActivity
(middle activity) and ThirdActivity
(last activity). They have a feature through which the first activity opens the second activity and the second activity opens the third activity closing itself. Now, the third activity has to send the result back to the first activity.
In this article, we will take a look at this scenario where we have to send the result from the last activity and read it in the first activity.
As usual, we start the middle activity for the result from the first activity.
// Open the middle activity
startActivityForResult(
Intent(context,
SecondActivity::class.java),
REQUEST_CODE_FETCH_RESULT
)
From the middle activity, we open the final activity (i.e., last activity) and close the current activity (i.e., middle activity). When invoking the last activity, we need to add an additional intent flag named
FLAG_ACTIVITY_FORWARD_RESULT
. This flag tells the system to pass the result from the last activity to the first activity.// Open the last activity
val intent = Intent(context, ThirdActivity::class.java).apply {
// Flag to transfer the ability to set the result
addFlags(FLAG_ACTIVITY_FORWARD_RESULT)
}
// Open the third activity
startActivity(intent)
// Close the middle activity
activity?.finish()
We close the last activity by setting the result and passing an intent with bundle extras. This will be helpful in the next step to validate that we have received the extras successfully.
// Set the result
val intent = Intent().apply {
// Intent extras
putExtra(BUNDLE_EXTRA_ACTIVITY_FINISHED, true)
}
activity?.run {
// Set the result
setResult(RESULT_OK, intent)
// Close the last activity
finish()
}
Now, the result is received at the first activity in the
onActivityResult
method.if (requestCode == REQUEST_CODE_FETCH_RESULT) {
if (resultCode == RESULT_OK) {
// Result is successfully set at the final activity
if (DBG) Log.d(TAG, "Result is OK")
// Read the bundle extra
val isFinished = data?.getBooleanExtra(
BUNDLE_EXTRA_ACTIVITY_FINISHED,
false
)
if (DBG) Log.d(TAG, "Is finished: $isFinished")
} else {
// User cancelled
if (DBG) Log.d(TAG, "Result is cancelled")
}
}
The boolean variable
BUNDLE_EXTRA_ACTIVITY_FINISHED
passed through the intent from the last activity is received at the first activity. We can see its value in the Android Studio logcat.
We can add as many activities as possible between the first, last activity and the bundle extras are received at the first activity as long as the activities are launched with the added intent flag
FLAG_ACTIVITY_FORWARD_RESULT
.