Android: Sending data from one Activity to another

6 August 2012 By Nithya Vasudevan 25,099 views 6 Comments
11 Flares Twitter 1 Facebook 7 Google+ 3 11 Flares ×

Project Description

  • In this Android tutorial, we will create an example to send data from one activity to another. This example creates two activities (FormActivity and DisplayActivity) each doing the following functions,
    • FormActivity – this is the main activity which is presented to the user when launching the application for the first time. It displays a form and allows the user to fill and submit the form. When submitted, it retrieves the values filled by the user and stores as Bundle in Intent and starts another activity – DisplayActivity. Uses form.xml as layout file to display the form.
    • DisplayActivity – it retrieves the Bundle from Intent which has values filled by the user and display it by setting the value of view elements. Uses display.xml as layout file to display the result.

Environment Used

  • JDK 6 (Java SE 6)
  • Eclipse Indigo IDE for Java EE Developers (3.7.1)
  • Android SDK 4.0.3 / 4.1 Jelly Bean
  • Android Development Tools (ADT) Plugin for Eclipse (ADT version 20.0.0)

Setting up development environment

To run this example, you need to setup the development environment with at least one Android platform in your SDK environment. To install Android SDK and configure ADT plugin for Eclipse read this page .

Prerequisites

Before proceeding with this example, it is recommended that you have completed this HelloWorld example which explains about creating Android project, its structure, components and how to run it in Eclipse IDE.

Android Project

Create an Android project and name it as “ActivityDemo“.

strings.xml

Open res/values/string.xml and replace it with following content.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Form</string>
    <string name="display">Display</string>
    <string name="app_name">ActivityDemo</string>
    <string name="name">Name</string>
    <string name="age">Age</string>
    <string name="female">Female</string>
    <string name="male">Male</string>
    <string name="gender">Gender</string>
    <string name="submit">Submit</string>    
</resources>

XML layout files

This application uses two layout files,

res/layout/form.xmlRepresents first screen used by FormActivity.java
res/layout/display.xmlRepresents second screen used by DisplayActivity.java

Create a new xml file in res/layout and name it as form.xml and copy the following content.
form.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:id="@+id/nameText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="18dp"
        android:layout_marginTop="24dp"
        android:text="@string/name" />

    <EditText
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/nameText"
        android:ems="10" android:inputType="text"/>

    <TextView
        android:id="@+id/ageText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/nameText"
        android:layout_below="@+id/name"
        android:layout_marginTop="26dp"
        android:text="@string/age" />

    <EditText
        android:id="@+id/age"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/ageText"
        android:ems="10" android:inputType="text"/>

    <TextView
        android:id="@+id/genderText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/gridLayout1"
        android:layout_below="@+id/age"
        android:layout_marginTop="19dp"
        android:text="@string/gender" />
    
    <GridLayout
        android:id="@+id/gridLayout1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/ageText"
        android:layout_below="@+id/age"
        android:layout_marginTop="44dp" >

        <RadioGroup
            android:id="@+id/gender"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

            <RadioButton
                android:id="@+id/femaleRadio"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:checked="true"
                android:text="@string/female" />

            <RadioButton
                android:id="@+id/maleRadio"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:checked="true"
                android:text="@string/male" />
        </RadioGroup>
    </GridLayout>

    <Button
        android:id="@+id/submit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/gridLayout1"
        android:layout_below="@+id/gridLayout1"
        android:layout_marginTop="21dp"
        android:text="@string/submit" />
</RelativeLayout>

Create a new xml file in res/layout and name it as display.xml and copy the following content.
display.xml

<?xml version="1.0" encoding="utf-8"?>
    <GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:columnCount="3" >

        <TextView
            android:id="@+id/nameText"
            android:layout_column="1"
            android:layout_gravity="left"
            android:layout_row="1"
            android:text="@string/name" />

        <TextView
            android:id="@+id/nameValue"
            android:layout_column="2"
            android:layout_gravity="left"
            android:layout_row="1"
            android:text=""
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <TextView
            android:id="@+id/ageText"
            android:layout_column="1"
            android:layout_gravity="left"
            android:layout_row="3"
            android:text="@string/age" />

        <TextView
            android:id="@+id/ageValue"
            android:layout_column="2"
            android:layout_gravity="left"
            android:layout_row="3"
            android:text=""
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <TextView
            android:id="@+id/genderText"
            android:layout_column="1"
            android:layout_gravity="left"
            android:layout_row="5"
            android:text="@string/gender" />

        <TextView
            android:id="@+id/genderValue"
            android:layout_column="2"
            android:layout_gravity="left"
            android:layout_row="5"
            android:text=""
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <Space
            android:layout_width="21dp"
            android:layout_height="1dp"
            android:layout_column="0"
            android:layout_gravity="fill_horizontal"
            android:layout_row="0" />

        <Space
            android:layout_width="1dp"
            android:layout_height="21dp"
            android:layout_column="0"
            android:layout_gravity="fill_horizontal"
            android:layout_row="0" />

        <Space
            android:layout_width="64dp"
            android:layout_height="1dp"
            android:layout_column="1"
            android:layout_gravity="fill_horizontal"
            android:layout_row="0" />

        <Space
            android:layout_width="1dp"
            android:layout_height="10dp"
            android:layout_column="0"
            android:layout_gravity="fill_horizontal"
            android:layout_row="2" />

        <Space
            android:layout_width="1dp"
            android:layout_height="10dp"
            android:layout_column="0"
            android:layout_gravity="fill_horizontal"
            android:layout_row="4" />
    </GridLayout>

Activity

In src folder, create a new Class and name it as “FormActivity” in the package “com.theopentutorials.android” and copy the following code.

FormActivity.java

package com.theopentutorials.android;

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.RadioButton;
import android.widget.RadioGroup;

public class FormActivity extends Activity implements OnClickListener {
	Button button;
	RadioGroup genderRadioGroup;
	EditText name;
	EditText age;

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

		//Get the ids of view objects
		findAllViewsId();
		
		button.setOnClickListener(this);
	}

	private void findAllViewsId() {
		button = (Button) findViewById(R.id.submit);
		name = (EditText) findViewById(R.id.name);
		age = (EditText) findViewById(R.id.age);
		genderRadioGroup = (RadioGroup) findViewById(R.id.gender);
	}
	
	@Override
	public void onClick(View v) {
		Intent intent = new Intent(getApplicationContext(), DisplayActivity.class);
		//Create a bundle object
		Bundle b = new Bundle();
		
		//Inserts a String value into the mapping of this Bundle
		b.putString("name", name.getText().toString());
		b.putString("age", age.getText().toString());
		int id = genderRadioGroup.getCheckedRadioButtonId();
		RadioButton radioButton = (RadioButton) findViewById(id);
		b.putString("gender", radioButton.getText().toString());
		
		//Add the bundle to the intent.
		intent.putExtras(b);
		
		//start the DisplayActivity
		startActivity(intent);
	}
}

Here, the button is registered to the android.view.View.OnClickListener using the method button.setOnClickListener(). When the event occurs it calls onClick() method.

We create an Intent object to activate another activity (DisplayActivity). Intent object is created using one of its constructors which takes a Context of the application package implementing this class and the component class that is to be used for the intent.

public Intent (Context packageContext, Class cls)

In our example, we use,

Intent intent = new Intent(getApplicationContext(), DisplayActivity.class);

To pass data between activities, we create a Bundle object and add values (name, age, gender) and stuff this bundle object in the intent by calling the method putExtras().

In src folder, create another Class and name it as “DisplayActivity” in the same package and copy the following code.

DisplayActivity.java

package com.theopentutorials.android;

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

public class DisplayActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        	setContentView(R.layout.display);

		Bundle b = getIntent().getExtras();
		TextView name = (TextView) findViewById(R.id.nameValue);
		TextView age = (TextView) findViewById(R.id.ageValue);
		TextView gender = (TextView) findViewById(R.id.genderValue);
		
		name.setText(b.getCharSequence("name"));
		age.setText(b.getCharSequence("age"));
		gender.setText(b.getCharSequence("gender"));
	}
}

The above code works as follows,

  • Retrieve bundle object from intent.
  • Find the id for view objects defined by display.xml
  • Get the value from bundle and set it in the view objects

AndroidManifest.xml

Define the two activities in AndroidManifest.xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.theopentutorials.android"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".FormActivity"
            android:label="@string/hello" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name=".DisplayActivity"
            android:label="@string/display" >
        </activity>
    </application>
</manifest>

Output

Run your application.

Project Folder Structure

The complete folder structure of this example is shown below.

Tags: , , , , , , , , , , , , , ,

  • janath

    Hi I’m new to android,I have some error “R cannot be resolved to a variable” in all java page.I include import my package name.*; also.whats the solution for this problem

    • http://daringdudes.in Nandan

      use build – > clean project

  • umar zia

    Thank you for this material I am teaching my students from your website. Thanks a lot… I am really making good money and repute… :P

  • Nilesh

    Thanks for the code… I works like charm

  • Mr-Hello

    Awesome-tutorials !

  • Nicky Larson

    Thank you very much for this nice tutorial !