How to transfer data between Activities in Android?

SHARE & COMMENT :

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.

In this sample app I will be using the below two Activities.

  1. Activity_SendData.java (for sending data)
  2. Activity_ReceiveData.java (for receiving data)

Below are the two layouts.

  1. layout_senddata.xml
  2. layout_receivedata.xml

Below is the Complete Project Structure.

transfer_prjct_structure

Prerequisites:

You must have enough knowledge on

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).

Open the activity Activity_SendData.java and paste the below code.

package my.app;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Activity_SendData extends Activity {

	EditText edit_name;
	Button btn_ok;
	String name;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_senddata);

		edit_name=(EditText)findViewById(R.id.EditText01);
		btn_ok=(Button)findViewById(R.id.Button01);

		//"Ok" Button listener
		btn_ok.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				name=edit_name.getText().toString();
				System.out.println("name:"+name);

				//Checking whether the EditText is empty or not
				if((name.equals(""))==false){

					//Creating a new intent
					Intent intent=new Intent(Activity_SendData.this, Activity_ReceiveData.class);

					//Sending data to next activity using putExtra method
					intent.putExtra("NAME", name);

					//starting new activity
					startActivity(intent);
				}
				else{
					Toast.makeText(Activity_SendData.this, "Please Enter your name", 1000).show();
				}
			}
		});
	}
}

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.

package my.app;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class Activity_ReceiveData extends Activity{
	TextView txt1;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_receivedata);
		//taking the textview1 reference
		txt1=(TextView)findViewById(R.id.TextView01);

		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);
		}
	}
}

Now your activities are ready.

Step 3: Create the required layouts.

The main.xml is the default layout that your application has. You can always edit it to suit your requirement or you can create your own layout file for your launcher activity.

Create the two layout files layout_senddata.xml and layout_receivedata.xml. If you have any queries on how to create a new layout file,please refer the post create a layout file.

I have used layout_senddata.xml for my launcher activity. Double click on the layout_senddata.xml and paste the below code.

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout android:id="@+id/RelativeLayout01"
	android:layout_width="fill_parent" android:layout_height="fill_parent"
	xmlns:android="http://schemas.android.com/apk/res/android">
	<TextView android:id="@+id/TextView01" android:layout_width="wrap_content"
		android:layout_height="wrap_content" android:text="Enter your Name"
		android:textStyle="bold" android:textSize="15sp"
		android:layout_marginTop="10dip">
	</TextView>
	<EditText android:id="@+id/EditText01" android:layout_below="@id/TextView01"
		android:layout_height="wrap_content" android:layout_width="200dip">
	</EditText>
	<Button android:id="@+id/Button01" android:layout_below="@id/EditText01"
		android:text="OK" android:layout_height="50dip" android:layout_width="50dip">
	</Button>
</RelativeLayout>

As you can see in the above code I have used an edittext to take the name and used a button “OK” to navigate to next page.

Now open the layout_receivedata.xml and paste the below code:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="@+id/RelativeLayout01"
	android:layout_width="fill_parent" android:layout_height="fill_parent"
	xmlns:android="http://schemas.android.com/apk/res/android">
	<TextView android:id="@+id/TextView01" android:layout_width="wrap_content"
		android:layout_height="wrap_content" android:textStyle="bold"
		android:textSize="15sp" android:text="Hi"
		android:layout_centerHorizontal="true" android:layout_marginTop="80dip">
	</TextView>
	<TextView android:id="@+id/TextView02" android:layout_width="wrap_content"
		android:layout_height="wrap_content" android:layout_centerInParent="true"
		android:text="welcome to second activity" android:textSize="15sp"
		android:textStyle="bold">
	</TextView>
</RelativeLayout>

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

The complete code of the manifest file is as below:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
	package="my.app" android:versionCode="1" android:versionName="1.0">
	<application android:icon="@drawable/icon" android:label="@string/app_name">
		<activity android:name=".Activity_SendData" android:label="@string/app_name">
			<intent-filter>
				<action android:name="android.intent.action.MAIN" />
				<category android:name="android.intent.category.LAUNCHER" />
			</intent-filter>
		</activity>
		<!-- Defining the new activity -->
		<activity android:name="Activity_ReceiveData"></activity>
	</application>
	<uses-sdk android:minSdkVersion="8" />
</manifest>

Step 5: Run the project

Select the project->Run As->Android Application

Your first activity Activity_SendData fires up as below.

transfer11

when you click on “OK”, your second activity Activity_ReceiveData Opens up. That displays the name that you have entered in previous screen.

transfer_otp2

This is how you can transfer data between activities. If you have any questions or find any error in this article,Please post in the comment section.

Comments

comments

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.

Comments

  1. What is the benefit of using intents instead of global application context (besides the app context is a singleton)?

Speak Your Mind

*

Close
Please support the site
By clicking any of these buttons you help our site to get better