Android StartActivityForResult - Androhub

StartActivityForResult Banner

Android StartActivityForResult

In Android we can pass data from one activity to another via Intent using startActivity(). The syntax for this is shown below :

Similarly we can get data from our other activity that is opened by an activity like SecondActivity from MainActivity and we need some message from SecondActivity back again to MainActivity so for this we need startActivityForResult(). Below is syntax of startActivityForResult that is in MainActivity.

Here 2 is request code for this activity and make sure no two activity have same request code.

Now in SecondActivity we send back result via intent. While sending back intent we have to setResult()  :

  • RESULT_OK : This refers the result send is ok.
  • RESULT_CANCELED : This means the activity cancel to send result.

Finally in MainActivity class we have to get result in onActivityResult() method and check the request code and result code and do according to it.

Example

In this tutorial, we are going to learn how to get result back from an activity using startActivityForResult.

VIDEO DEMO

1. Create a new project in Android Studio by navigating to File ⇒ New Android ⇒ Application Project and fill required details. By default my activity is MainActivity.java.

2. Open res=>values=>strings file and add the following strings.

3. Create a layout xml file naming activity_main.xml and add the following code. In this i had taken one TextView that will display return message from second activity and a Button that will open second activity.

4. Now create a new xml file naming second_activity.xml and add the following code. In this we are having an EditText for take user input and a two Button one for Cancel and one for Submit.

5. Open your MainActivity.java and the following code. In this code i have used all steps mentioned at starting.

6. Now create a new java file naming SecondActivity.java and add the following code. In this class i am returning message on Submit button click and cancelling activity on Cancel button click.

7. Finally come to your Manifest file and add your SecondActivity.

8. Now, you are all done, run your app and you will get the output as shown in video.

Thanks. :)

 

Post comment

Your email address will not be published. Required fields are marked *