Passing Data Between Activities in Android

This tutorial will show you how to pass data between activities using Bundle and attaching it to Intent to pass the required data between two activities.

Step 1: Create a Bundle with the data

First you need to create a Bundle in the activity from which you want to pass the data from.
To the Bundle add the data elements with keys.
The following code shows how to create a bundle and data to it:

        Bundle bundle = new Bundle();
        // putInt(String Key, int Value)
        bundle.putInt("Score",1000231);
        // putString(String Key, String Value)
        bundle.putString("Name","Anuraag");
        // putBoolean(String Key, boolean Value)
        bundle.putBoolean("Winner",true);

Bundle Create

Step 2: Create the Intent to start new Activity and attach Bundle

Next you need to create the Intent that starts the new activity. And then attach the Bundle you just created.
The following code shows how to create an Intent and how to attach the bundle to the Intent:

Intent nIntent = null;
        try {
            nIntent = new Intent(MainActivity.this,Class.forName("com.anuraag.myapplication.NewActivity"));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        if(nIntent!=null){
            //pass the Bundle that you created earlier.
    nIntent.putExtras(bundle);
        }

Bundle Attach

Reminder: After attaching the bundle to the Intent you need to start the new Activity.

Step 3: Receive and Read the data passed

Now that the data is passed using the intent you need to get the bundle from the Intent in the new activity that the Intent was used to start. Then you can read or get the data present in the Bundle using get methods.
The following code shows how to extract the Bundle from the Intent and then how to read the data:

// get the intent that started this activity using getIntent() method.
        Intent sIntent = getIntent();
        // get the bundle attached to the intent using getExtras() method.
        Bundle bundle = sIntent.getExtras();
        //following methods can be used to retrieve the data
        // getString(String Key) , the Key has to be same as the key entered while adding the data
        String name = bundle.getString("Name");
        int Score = bundle.getInt("Score");
        boolean winner = bundle.getBoolean("Winner");

Retrieve Data

The data passed now can be used by the new activity to display, save over the cloud or save on the internal storage.
Another way to pass data between activities is to use SharedPreferences.

This content has been helpful to you?

Thanks for contributing!

Yes No