How to pass data from one activity to other activity
Today, we are going to see how we can send data from one activity to the second activity.
So let's get started,
First, create a new project if you do not create already.
Then open your first activity xml file and we are going to add a button.
This button will be our trigger to open the second activity. So to do that we need to create a button and set on click listener.
Remove textview created by the android studio by default and add a new button like the below image.
Note that I have changed my parent layout from ConstraintLayout to LinearLayout which is optional.
I have specified id to the button e.g openAcitivityButton.
Now it's time set click listener. To do that we need to open our activity java file.
At this point, we have only one activity to open the next activity we need to make new activity.
To do this, right-click on an app in the project section, click on the new then activity and select an empty activity. See the gif below.
We name the second activity as SecondActivity.
Now, open the second activity xml file and add a textview with the id of textview.
We will use the textview to show the first activity data which we will pass.
Your xml file should look like this.
Now, open your first activity java file and in the button click listener, we add this code.
And in the next line, to pass data we use the putExtra method which accepts key and value.
Then we start our activity.
We will access the data in the second activity by using the key. Open your second activity and write this code in your onCreate method.
In the first line, we are getting the data from the intent and we access this data by the "data" key.
Which we have set in the previous activity. Then,
We are setting data for our textview of the second activity.
Now run your app and tap on the first activity button and you will see our data successfully passed to the next activity.
Hope you learn something new. Share this article with your friends and mates. Thank You.