Categories
android android-activity android-intent startactivityforresult

How to manage startActivityForResult on Android

1085

In my activity, I’m calling a second activity from the main activity by startActivityForResult. In my second activity, there are some methods that finish this activity (maybe without a result), however, just one of them returns a result.

For example, from the main activity, I call a second one. In this activity, I’m checking some features of a handset, such as does it have a camera. If it doesn’t have then I’ll close this activity. Also, during the preparation of MediaRecorder or MediaPlayer if a problem happens then I’ll close this activity.

If its device has a camera and recording is done completely, then after recording a video if a user clicks on the done button then I’ll send the result (address of the recorded video) back to the main activity.

How do I check the result from the main activity?

1

2619

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

For example:

int LAUNCH_SECOND_ACTIVITY = 1
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();
returnIntent.putExtra("result",result);
setResult(Activity.RESULT_OK,returnIntent);
finish();

If you don’t want to return data:

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

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

@Override
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.

17

  • 2

    What is the purpose of putting an intent when RESUT_CANCELLED in setResult(RESULT_CANCELED, returnIntent);

    Oct 30, 2013 at 23:05


  • 4

    @ismail Suppose in the SecondActivity some exception occurred, in that case also you need to return the result to the FirstActivity,so you can set the result as "RESULT_CANCELLED" in the catch block and return to FirstActivty and in FirstActivity's' 'onActivityResult() you can check whether you got the success or failure result.

    – Nishant

    Oct 31, 2013 at 4:42

  • 13

    So it’s up to you, if you don’t need to know the reason for cancelling, you can use just setResult(RESULT_CANCELED); without any intent

    Oct 31, 2013 at 10:43


  • 2

    @Lei Leyba No finish() is not called after calling startActivityForResult().First Actvity will move to pause state.

    – Nishant

    Oct 1, 2014 at 6:26


  • 9

    For me it is not working -.- this is what I hate soooo much about Android – this system is so unreliable :-/

    Mar 9, 2015 at 21:51

55

How to check the result from the main activity?

You need to override Activity.onActivityResult() and then check its parameters:

  • requestCode identifies which app returned these results. This is defined by you when you call startActivityForResult().
  • resultCode informs you whether this app succeeded, failed, or something different
  • data holds any information returned by this app. This may be null.

1

  • It means that the requestCode is only used in the first activity, and it is never used for the 2nd activity? If the 2nd activity has different approaches, it would change, but based in the intent extras and not by the requestCode, right? Edit: Yes, stackoverflow.com/questions/5104269/…

    – JCarlosR

    Aug 11, 2017 at 23:32


53

Example

To see the entire process in context, here is a supplemental answer. See my fuller answer for more explanation.

enter image description here

MainActivity.java

public class MainActivity extends AppCompatActivity {

    // Add a different request code for every activity you are starting from here
    private static final int SECOND_ACTIVITY_REQUEST_CODE = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    // "Go to Second Activity" button click
    public void onButtonClick(View view) {

        // Start the SecondActivity
        Intent intent = new Intent(this, SecondActivity.class);
        startActivityForResult(intent, SECOND_ACTIVITY_REQUEST_CODE);
    }

    // This method is called when the second activity finishes
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // check that it is the SecondActivity with an OK result
        if (requestCode == SECOND_ACTIVITY_REQUEST_CODE) {
            if (resultCode == RESULT_OK) { // Activity.RESULT_OK

                // get String data from Intent
                String returnString = data.getStringExtra("keyName");

                // set text view with string
                TextView textView = (TextView) findViewById(R.id.textView);
                textView.setText(returnString);
            }
        }
    }
}

SecondActivity.java

public class SecondActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
    }

    // "Send text back" button click
    public void onButtonClick(View view) {

        // get the text from the EditText
        EditText editText = (EditText) findViewById(R.id.editText);
        String stringToPassBack = editText.getText().toString();

        // put the String to pass back into an Intent and close this activity
        Intent intent = new Intent();
        intent.putExtra("keyName", stringToPassBack);
        setResult(RESULT_OK, intent);
        finish();
    }
}

1