How to transfer data between Activities in Android?

In Mobile app development you will come across many situations wherein you will have to send data from one activity to another. It is one of the most challenging part in the mobile application development. This tutorial describes how you can transfer data between activities in Android application.

Prerequisites:

Basic functionality of the App:

Here in this App we will be sending a data(name) from the activity Activity_SendData.java to Activity_ReceiveData.java. In the second activity we are retrieving it and displaying it in the textview.

Follow the below steps to create the Application.

Step 1: Create an Android project

Create an Android Project in the name “data_tranfer” where layout_senddata.xml is a launcher activity.

If you have any doubts on how to create an android project please go through the post create an android app.

Step 2: Create the Activities.

The activity Activity_SendData.java will be automatically created when you create your app since it is a launcher activity. Create Another Activity Activity_ReceiveData.java. If you have any doubts on how to create a new activity please refer create new activity .

The below is the code snippet that you need to use to send data.

intent.putExtra("NAME", name);

As you can notice in the above code we have used putExtra method to send the data to next activity. This method accepts the data as KEY-VALUE pair where VALUE is retrieved in the second activity using the KEY. There are many variants of putExtra method using which you can send any kind of data. There are number of value types that can be included into the extras of intent (for instance, int, int[], Bundle, Parcelable, and so on).

Now we will see how we can make the second activity to receive the data which we are sending using first activity.
For that we have to use the below code snippet in your activity Activity_ReceiveData.

Bundle bunble=getIntent().getExtras();
if(bunble!=null){
//Getting the value stored in the name "NAME"
String user_name=bunble.getString("NAME");
//appending the value to the contents of textView1.
txt1.append(" "+user_name);

We make use of getIntent().getExtras() method to retrieve the data and We are appending that value to the textview1.

Open the newly created activity Activity_ReceiveData.java and paste the below code.

Here I am appending the data that I have received from the previous page to the contents of the textview1.

Step 4: Define the Activities in Manifest file

This is a very important step. If you do not define your activities in the manifest,the system will not recognize them. If you have any queries regarding AndroidManifest.xml,please refer AndroidManifest.xml

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.