How to manage 'startActivityForResult' on Android

Asked 1 years ago, Updated 1 years ago, 95 views

Recall the second activity through startActivityForResult from one activity. The second activity contains several functions that terminate it. Normally, it does not return a result value, but only one function returns a result value.

For example, the main activity calls the second activity. This activity checks for some equipment, such as whether the device has a camera. If the equipment does not exist, terminate the activity. Similarly, if you encounter problems preparing for MediaRecorder or MediaPlayer, exit the activity.

If the camera exists and the recording ends normally, the user presses the Finish button to complete the recording and returns the result (address of the recorded video) to the main activity.

How do I check the results in the main activity?

android android-intent

2022-09-22 08:33

1 Answers

As shown below, FirstActivity calls SecondActivity using startActivityForResult() function.

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

SecondActivity sets the data to be returned to FirstActivity, and if there is no value to return, you do not need to set any value.

For example, if SecondAcity has a value to return:

Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(Activity.RESULT_OK,returnIntent);
finish();

Conversely, if there is no value to return:

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

It can be configured as shown in . In the FirstActivity class, you can configure the following code in the onActivityResult() function.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == 1) {
        if(resultCode == Activity.RESULT_OK){
            String result=data.getStringExtra("result");
        }
        if (resultCode == Activity.RESULT_CANCELED) {
            //If there is no return value, write the code here.
        }
    }
}//onActivityResult


2022-09-22 08:33

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.