A mapping used to pass data between various Activities & Fragments in Android
A Bundle
is a mapping from String
values to various Parcelable
types.
It is used in Android to store and retrieve datas inside an Activity
when the orientation changed or to pass these values between two Activities. You can also used a Bundle
to pass data between Activity
and Fragments
.
Its initialization is as follows:
Bundle b = new Bundle();
// Put values (ex: a String):
b.putString("value_name",value);
Then, it is related to an Intent
and pass to a new Activity with this Intent:
Intent intent = new Intent(ActivityA.this,ActivityB.class);
intent.putExtras(b);
startActivity(intent) // launch ActivityB and pass the Bundle to it
This map allows multiples types and retrieve its values inside the new Activity as follows:
Bundle extras = getIntent().getExtras();
String received_value = extras.getString("value_name");
When the device does a rotation, the Activity is destroyed and recreated. The datas can be stored to avoid to lost some informations:
By default, the system uses the Bundle instance state to save information about each View object in your activity layout (such as the text value entered into an EditText object).`
In similar fashion you can use bundles to pass data between fragment :-
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.setArguments(bundle);
Bundle has put methods for lots of data types.
Then in your Fragment, retrieve the data (e.g. in onCreate() method) with:
Bundle bundle = this.getArguments();
int myInt = bundle.getInt(key, defaultValue);
See the SO question What is a "bundle" in an Android application
Also the Recreating an Activity topic from Google Documentation
For more information, read the reference in Documentation: Bundle
Related tags: android, bundle,
android-intent,
android-activity