Request Result Using startActivityForResult and Listen to It in onActivityResult

Let us say we have two activities (First Activity and Second Activity) in our Android application then startActivityForResult() is used by the First Activity when it expects a result from the Second Activity and onActivityResult() is used to read the returned result from the Second Activity.

In simple terms, we can send information to the top activity in the back stack.

From our First Activity, start the Second Activity with a request code.

// Open the second activity
startActivityForResult(
        Intent(context,
                SecondActivity::class.java),
        REQUEST_CODE_FETCH_RESULT
)

This opens the Second Activity. When we are done with the Second Activity and want to pass the data back to the First Activity, we call setResult and close our Second Activity.

// Set the result in the Second Activity
val intent = Intent().apply {
    // Intent extras
    putExtra(BUNDLE_EXTRA_ACTIVITY_FINISHED, true)
}
activity?.run {
    // Set the result
    setResult(RESULT_OK, intent)
    // Close the Second activity
    finish()
}

We read the result in the First Activity using the overridden method onActivityResult.

// Read the data received
if (requestCode == REQUEST_CODE_FETCH_RESULT) {
    if (resultCode == RESULT_OK) {
        // Result is successfully set at the Second 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")
    }
}

Only thing to remember is to pass a positive number as the request code. In case a negative number is passed, the result is not received in onActivityResult as startActivity is invoked and not startActivityForResult.

Popular posts from this blog

Add Spacing to Recycler View Linear Layout Manager Using Item Decoration

Perform a Post Request Using Volley

Bottom App Bar for Android - A Material Design Component

How to Set an Android App as a Default Dialer

How to Change Material Chip Text Size, Text Style and Font