How to manage startActivityForResult on Android

From your FirstActivity, call the SecondActivity using the startActivityForResult() method.

For example:

Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, LAUNCH_SECOND_ACTIVITY);

In your SecondActivity, set the data which you want to return back to FirstActivity. If you don’t want to return back, don’t set any.

For example: In SecondActivity if you want to send back data:

Intent returnIntent = new Intent();

If you don’t want to return data:

Intent returnIntent = new Intent();
setResult(Activity.RESULT_CANCELED, returnIntent);

Now in your FirstActivity class, write the following code for the onActivityResult() method.

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == LAUNCH_SECOND_ACTIVITY) {
        if(resultCode == Activity.RESULT_OK){
            String result=data.getStringExtra("result");
        if (resultCode == Activity.RESULT_CANCELED) {
            // Write your code if there's no result
} //onActivityResult

To implement passing data between two activities in a much better way in Kotlin, please go through ‘A better way to pass data between Activities’.

Leave a Comment