Android – Passing Data to Another Activities

android-pass-data-to-activity

You can start another activity within the same application by calling startActivity(), passing it an Intent that describes the activity you want to start. Also you can pass some data to the activity “to be started”, using the Intent object too.

Objectives:

  • How to pass data to other activities?
  • How to put the data in Intent object?

Environment & Tools:

  • Android Developer Tools (ADT) (or Eclipse + ADT plugin)
  • AVD Nexus S Android 4.3 “emulator”
  • Min SDK 8

( 1 ) Create Android Application

  • File >> New >> Android Application
  • Enter Project name: android-pass-data-activity
  • Pakcage: com.hmkcode.android
  • Keep other defualt selections, go Next  till you reach Finish

( 2 ) Two Layouts for Two Activities

  • Define the layout for the first “main” activity and the second “another” activity to be started.
  • res/layout/activity_main.xml
  • The layout contains a button to call & pass data another activity.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/tvHelloWorld"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/btnPassData"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tvHelloWorld"
        android:layout_marginTop="26dp"
        android:layout_centerHorizontal="true"
        android:text="Pass Data to Another Activity" />

</RelativeLayout>
  • res/layout/activity_another.xml
  • The layout contains one TextView to display a message sent from the starter activity.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tvMessage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

( 3 ) Two Activity Classes

  • src/com/hmkcode/android/ActivityMain.java
  • MainActivity.java is a simple “starter” activity class implementing OnClickListener to handle button click event.
  • When user click on the button we call onClick
  • Within the onClick method we create the intent, put some data and pass it to startActivity(intent) method.
  • The data can be inserted directly into the intent using putExtras(key,value) or we first add it to a bundle then we put it in the intent.
package com.hmkcode.android;

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

public class MainActivity extends Activity implements OnClickListener {

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

		btnStartAnotherActivity = (Button) findViewById(R.id.btnPassData);

		btnStartAnotherActivity.setOnClickListener(this);
	}

	@Override
	public void onClick(View view) {

		// 1. create an intent pass class name or intnet action name 
		Intent intent = new Intent("com.hmkcode.android.ANOTHER_ACTIVITY");

		// 2. put key/value data
		intent.putExtra("message", "Hello From MainActivity");

		// 3. or you can add data to a bundle
		Bundle extras = new Bundle();
		extras.putString("status", "Data Received!");

		// 4. add bundle to intent
		intent.putExtras(extras);

		// 5. start the activity
		startActivity(intent);
	}

}
  • src/com/hmkcode/android/AnotherActivity.java
  • AnotherActivity.java is the activity we want to start. It has one text view & a toast to display data “message & status” sent from the starter activity.
  • We can access to the sent data by getting a reference to the sent intent using getIntent();
  • Once we get the intent we can extract the data. Here we can extract the sent message getIntent().getStringExtra(“message”)
  • Also we can get the access to the attached bundle getIntent().getExtras() then we can extract the data from the bundle.
package com.hmkcode.android;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class AnotherActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_another);

		// 1. get passed intent 
		Intent intent = getIntent();

		// 2. get message value from intent
		String message = intent.getStringExtra("message");

		// 3. show message on textView 
		((TextView)findViewById(R.id.tvMessage)).setText(message);

		// 4. get bundle from intent
		Bundle bundle = intent.getExtras();

		// 5. get status value from bundle
		String status = bundle.getString("status");

		// 6. show status on Toast
		Toast toast = Toast.makeText(this, status, Toast.LENGTH_LONG);
		toast.show();
	}
}

( 4 ) Define Activities in the Manifest XML File

  • All activity should be defined with in the manifest.xml file
  • AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.hmkcode.android"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <activity
            android:name="com.hmkcode.android.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
			android:name="com.hmkcode.android.AnotherActivity"
			android:label="@string/app_name" >
			<intent-filter>
				<action android:name="com.hmkcode.android.ANOTHER_ACTIVITY" />
				<category android:name="android.intent.category.DEFAULT" />
			</intent-filter>
		</activity>
    </application>

</manifest>