What is a "bundle" in an Android application

I have to add that bundles are used by activities to pass data to themselves in the future.

When the screen rotates, or when another activity is started, the method protected void onSaveInstanceState(Bundle outState) is invoked, and the activity is destroyed. Later, another instance of the activity is created, and public void onCreate(Bundle savedInstanceState) is called. When the first instance of activity is created, the bundle is null; and if the bundle is not null, the activity continues some business started by its predecessor.

Android automatically saves the text in text fields, but it does not save everything, and subtle bugs sometimes appear.

The most common anti-pattern, though, is assuming that onCreate() does just initialization. It is wrong, because it also must restore the state.

There is an option to disable this "re-create activity on rotation" behavior, but it will not prevent restart-related bugs, it will just make them more difficult to mention.

Note also that the only method whose call is guaranteed when the activity is going to be destroyed is onPause(). (See the activity life cycle graph in the docs.)


Pass data between activities by using Bundle and Intent objects.


Your first create a Bundle object

Bundle b = new Bundle();

Then, associate the string data stored in anystring with bundle key "myname"

b.putString("myname", anystring);

Now, create an Intent object

Intent in = new Intent(getApplicationContext(), secondActivity.class);

Pass bundle object b to the intent

in.putExtras(b);

and start second activity

startActivity(in);

In the second activity, we have to access the data passed from the first activity

Intent in = getIntent();

Now, you need to get the data from the bundle

Bundle b = in.getExtras();

Finally, get the value of the string data associated with key named "myname"

String s = b.getString("myname");

Bundles are generally used for passing data between various Android activities. It depends on you what type of values you want to pass, but bundles can hold all types of values and pass them to the new activity.

You can use it like this:

Intent intent = new...
Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("myKey", AnyValue);  
startActivity(intent);

You can get the passed values by doing:

Bundle extras = intent.getExtras(); 
String tmp = extras.getString("myKey");

You can find more info at:

  • android-using-bundle-for-sharing-variables and

  • Passing-Bundles-Around-Activities