How To Pass Data Between Two Different Activities Using Intent In Android
Intent are asynchronous message which allows Android components to request functionality from other components of the Android system
In this tutorial. I will demonstrate how to pass the data forward and back from one Activity to another using Android Explicit Intent.
To pass the data we need to use putExtra() which has two parameters first is key and second value.
putExtra() : adds the extended data to Intent.
intent.putExtra("key", value);
To retrieve data from Second Activity we need to use getIntent() and getExtra() methods which return the type of Bundle. Bundle is basically a mapping from String values to various Parcelable types
getIntent() : returns the Intent that started this Activity.
getExtra() : fetch the data which was added using putExtra() in the following way.
Bundle bundle = getIntent().getExtra();
Now you can use different Bundle class methods to get the values passed from the first Activity. Example :
bundle.getString("key")
bundle.getInt("key")
bundle.getDouble("key")
Passing Data Between Activities Example:
Passing Data Forward
Step1 :
activity_main.xml
MainActivity.java
Step 2 :
activity_second.xml
SecondActivity.java
Passing Data Back
MainActivity
- Start the Second Activity with
startActivityForResult
, providing it an arbitrary result code. - Override
onActivityResult
. This is called when the Second Activity finishes. You can make sure that it is actually the Second Activity by checking the result code. (This is useful when you are starting multiple different activities from the same main activity.) - Extract the data you got from the return
Intent
. The data is extracted using a key-value pair.
Second Activity
- Put the data that you want to send back to the previous activity into an
Intent
. The data is stored in theIntent
using a key-value pair. - Set the result to
RESULT_OK
and add the intent holding your data. - Call
finish()
to close the Second Activity.
Step 1 :
activity_main.xml
MainActivity.java
Step 2 :
activity_second.xml
SecondActivity.java
Now we are done with the coding part, so run the app and test it.