Developer Tip #10: Passing Data Between Activities via Bundles
February 10, 2010 No CommentsThis might be one of things you do most often in Android programming. Say you have a nice activity that functions well. You want to program a second activity that runs after the first, but uses data gathered by the first. How do you do this?
Have no fear! Bundles are here. Bundles are controlled hashmaps that allow you to pass smalll quantized chunks of data between activities. To check out how they work, check out the following scenario:
I have some data in the form of stings, ints, etc that I want to pass between Activity1 and Activity2. How do I do this?
Simple. Create a bundle, populate the data into the bundle (using the handy dandy put() function). Attach the bundle to the intent you’re firing. Fire said intent and retrieve the values on the other side.
Here’s some code to illustrate this concept:
//Create the intent
Intent i = new Intent(NameOfThisFile.this, NameofSecondJavaFile.class);//Create the bundle
Bundle bundle = new Bundle();//Add your stuff
bundle.putString(“stuff”, “foo”);
bundle.putString(“morestuff”,”foo2”);
bundle.putInt(“yourMomsAge”, 83);//Add the bundle to the intent
i.putExtras(bundle);//Fire that second activity
startActivity(i);Now in your second activity retrieve your goodies:
//Get the bundle
Bundle bundle = getIntent().getExtras();//Extract the data like legs from a turducken…
String stuff = bundle.getString(“stuff”); //puts foo in stuff
int myMomsAge = bundle.getInt(“yourMomsAge”);
Hope this helps. This method can also be used to return information once an activity closes, but more about that later, along with program flow.
|
|
|
|
|
![]() |
Programming

