Sobes.tech
Junior — Middle

How can you get the result returned from the next Activity in Android?

sobes.tech AI

Answer from AI

To get a result from the next Activity in Android, traditionally, the startActivityForResult() method is used. You launch a new Activity with an expectation of a result, and then override the onActivityResult() method to handle the returned data.

Example:

// Launch Activity expecting a result
Intent intent = new Intent(this, NextActivity.class);
startActivityForResult(intent, REQUEST_CODE);

// Handle the result
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
        String result = data.getStringExtra("result_key");
        // Use the result
    }
}

In the next Activity, set the result before finishing:

Intent resultIntent = new Intent();
resultIntent.putExtra("result_key", "some data");
setResult(RESULT_OK, resultIntent);
finish();

Starting with AndroidX, it is recommended to use ActivityResultLauncher and the Activity Result API, which are more convenient and safer, but startActivityForResult is still widely used.