Skip to main content

Pass Data between Activities

How to pass data from one activity to other activity

pass data 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.

android activity xml

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.

In the above code, we initialize our button name it as openActivityButton with its's id and then we are calling method setOnClickListener in the onCreate method.

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.

create new activity in android studio

We name the second activity as SecondActivity.

create new activity in android studio

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.

android activity xml

Now, open your first activity java file and in the button click listener, we add this code.

In the click listener, we create an Intent with context and second activity class.

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.

pass data one activity to second activity
Hope you learn something new. Share this article with your friends and mates. Thank You.

Popular Posts

Customize rating bar in android

Working with Bottom Navigation bar in Android [Full Guide]

Custom Switch in Android | | Android Tutorial