Recipe 1.2 Passing Data Between Activities

Android Versions
Level 1 and above
Source Code to Download at

The preceding recipe demonstrated how to launch another activity using the startActivity() method. One common task you need to perform when launching another activity is passing some data to it. For example, you might want to launch another activity to collect some user-related data, so you pass the name of the user to another activity. When the user has finished collecting all the data, the data also needs to be passed back to the calling activity. Hence, you need to be able to pass data back and forth between activities. This recipe shows you how.


You can make use of the Intent class to pass data to another activity. To pass primitive data types to another activity, you can use the putExtra() method, as the following code snippet shows:

package net.learn2develop.passingdata;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends Activity {

    public void onCreate(Bundle savedInstanceState) {
    public void onClick(View view) {
        Intent i = new 
        //---use putExtra() to add new key/value pairs---            
        i.putExtra("str1", "This is a string");
        i.putExtra("age1", 25);

The preceding statements ...

Get Android Application Development Cookbook: 93 Recipes for Building Winning Apps now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.