Recipe 1.2 Passing Data Between Activities

Android Versions
Level 1 and above
Permissions
None
Source Code to Download at Wrox.com
PassingData.zip

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.

Solution

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.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void onClick(View view) {
        Intent i = new 
                Intent("net.learn2develop.SecondActivity");
        //---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.