Passing Bundles Around Activities

When I first started dabbling with Android, it took me a while to understand the framework, and how data is passed between screens (which are known as 'Activities' in Android).


In this example, the main Activity (appropriately named 'MainActvity') will pass information to a sub-activity (called SecondaryActivity).  SecondaryActivity will allow you to alter that information and then return it to MainActivity. The bundle of information will be sent back and forth between the Activity objects via an Intent object.

  
In order to pass the information we'll create our Intent object and do two things with it before sending it off.  First, we'll specify SecondaryActivity as the target by passing it into the Intent's constructor.  Then we'll stuff the information into it (the information is stored in a 'Bundle' object that lives inside the Intent - the Bundle is created when you call the putExtras() method of the Intent object).  Once our Intent is ready to go, our MainActivity will simply launch it by passing it as a parameter into startActivityForResult().


When SecondaryActivity is created, it will check to see if an Intent is available. If so, it wil extract the data from the Bundle and put it into an EditText so that you can alter it.  Then you can click a button to send it back to MainActivity.  When the button is clicked, a new Intent is created with the updated information stuffed into a Bundle.  SecondaryActivity then calls setResult() which will return the information back to MainActivity.


It's important to note that when you pass information around like this, you'll have to add an entry into the AndroidManifest.xml file.  I always seem to forget this step.  You'll have to add the following line of code into the <application> section:

<activity android:name=".SecondaryActivity"/>

Here's the code...

This is the layout file for MainActivity (main.xml)...

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="MAIN ACTIVITY"/>
    <EditText android:id="@+id/editText1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
    <Button android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Click To Launch Secondary Activity"/>
</LinearLayout>

Here's the code for the MainActivity class...

package com.remwebdevelopment;

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

public class MainActivity extends Activity implements View.OnClickListener {
    private final int SECONDARY_ACTIVITY_REQUEST_CODE=0;
    private EditText mEditText1;
    private Button mButton1;
    //DONT FORGET: to add SecondaryActivity to the manifest file!!!!!
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mEditText1 = (EditText)findViewById(R.id.editText1);
        mButton1 = (Button)findViewById(R.id.button1);
        mButton1.setOnClickListener(this);
    }
    public void onClick(View view){
        if(view == mButton1){
            //create a new intent and specify that it's target is SecondaryActivity...
            Intent intent = new Intent(getApplicationContext(),SecondaryActivity.class);
            //load the intent with a key "myKey" and assign it's value
            //to be whatever has been entered into the text field...
            intent.putExtra("myKey",mEditText1.getText().toString());
            //launch the secondary activity and send the intent along with it
            //note that a request code is passed in as well so that when the
            //secondary activity returns control to this activity,
            //we can identify the source of the request...
            startActivityForResult(intent, SECONDARY_ACTIVITY_REQUEST_CODE);
        }
    }
    //we need a handler for when the secondary activity finishes it's work
    //and returns control to this activity...
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent){
        super.onActivityResult(requestCode, resultCode, intent);
        Bundle extras = intent.getExtras();
        mEditText1.setText(extras != null ? extras.getString("returnKey"):"nothing returned");
    }
}

Here's the layout file for SecondaryActivity (secondary_activity.xml)...

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView android:layout_width="fill_parent"
             android:layout_height="wrap_content"
             android:text="SECONDARY ACTIVITY"/>
    <EditText android:id="@+id/txtSecondary"
             android:layout_width="fill_parent"
             android:layout_height="wrap_content"/>
    <Button android:id="@+id/btnSecondary"
            android:text="Click To Return to Main Activity"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/>
</LinearLayout>

Finally, here's the code for the SecondaryActivity class...

package com.remwebdevelopment;

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

public class SecondaryActivity extends Activity{
    private EditText mEditText2;
    private Button mButton2;
    private String mIntentString;
   
    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
       
        setContentView(R.layout.secondary_activity);
       
        mEditText2 = (EditText)findViewById(R.id.txtSecondary);
        mButton2 = (Button)findViewById(R.id.btnSecondary);
        //add the event handler for the button...
        mButton2.setOnClickListener(new View.OnClickListener(){
            public void onClick(View view){
                mIntentString = mEditText2.getText().toString();
                //create a new intent...
                Intent intent = new Intent();
                //add "returnKey" as a key and assign it the value
                //in the textbox...
                intent.putExtra("returnKey",mEditText2.getText().toString());
                //get ready to send the result back to the caller (MainActivity)
                //and put our intent into it (RESULT_OK will tell the caller that
                //we have successfully accomplished our task..
                setResult(RESULT_OK,intent);
                //close this Activity...
                finish();
            }
        });
       
        //if the activity is being resumed...
        mIntentString = savedInstanceState != null ? savedInstanceState.getString("myKey"):null;
       
        //check to see if a Bundle is .
        if(mIntentString == null){
            //get the Bundle out of the Intent...
            Bundle extras = getIntent().getExtras();
            //check to see if "myKey" is in the bundle, if so then assign it's value
            // to mIntentString  if not, assign "nothing passed in" to mIntentString...
            mIntentString = extras != null ? extras.getString("myKey") : "nothing passed in";
        }
        //set the textbox to display mIntentString...
        mEditText2.setText(mIntentString);
    }

}

59 Comments - Average Rating:4.36

Comments:
You are great man!!! The best explanation ever! Greetings from Bulgaria! ;)
Rating: 5
Date Posted: March 20th, 2014


Wagon makes this easier

https://github.com/beplaya/Wagon
Rating: 5
Date Posted: March 18th, 2014


OMG... This is great. Thank you so much
Rating: 5
Date Posted: November 26th, 2013


Really nive waht about showing us a generic sample, like passing objects between the activities instead of just a string. Thanks.
Rating: 5
Date Posted: November 21st, 2013


really a great example
and a program tht i was looking for so long
thank u
Rating: 5
Date Posted: April 10th, 2013


Nice example
Rating: 4
Date Posted: January 29th, 2013


Thanks it was helpful
Rating: 3
Date Posted: December 11th, 2012


Thanks it was helpful
Rating: 3
Date Posted: December 11th, 2012



RECENT ARTICLES