Android tutorial - Android Start Activity For Result Example - android app development - android studio - android development tutorial
Learn android - android tutorial - Android start activity - android examples - android programs
What is Start Activity For Result
- Start Activity For Result is used to receive result back from android activity like if your starting camera application into your mobile phone then as the final result you want to display your captured photo on mobile phone screen.
- In Android, the start Activity(Intent) method is used to start a new activity, which will be placed at the top of the activity stack.
- It takes a single argument, an Intent, which describes the activity to be executed.
- However, sometimes we might want to get a result back from an activity when it ends.
- For example, you may start an activity that lets the user pick a person in a list of contacts; when it ends, it returns the person that was selected.
- To do this, you call the start Activity For Result(Intent, 'extraValue') version with a second parameter identifying the call.
- The result will come back through your Extra values, from getIntent().
- By the help of android startActivityForResult() method, we can get result from another activity.
- By the help of android startActivityForResult() method, we can send information from one activity to another and vice-versa. The android startActivityForResult method, requires a result from the second activity (activity to be invoked).
- In such case, we need to override the onActivityResult method that is invoked automatically when second activity returns result.
Method Signature
There are two variants of startActivityForResult() method.
- public void startActivityForResult (Intent intent, int requestCode)
- public void startActivityForResult (Intent intent, int requestCode, Bundle options)
Let's see the simple example of android startActivityForResult method.
activity_main.xml
- Drag one textview and one button from the pallete, now the xml file will look like this.
File: activity_main.xml
second_main.xml
- This xml file is created automatically when you create another activity. To create new activity Right click on the package inside the src -> New -> Other ->Android Activity.
- Now drag one editText, one textView and one button from the pallete, now the xml file will look like this:
File: second_main.xml
Activity class
- Now let's write the code that invokes another activity and get result from that activity.
File: MainActivity.java
Second Activity class
- Let's write the code that displays the content of second activity layout file.