Developer Tip #10: Passing Data Between Activities via Bundles

February 10, 2010 No Comments

This 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.

Add to Del.cio.us RSS Feed Add to Technorati Favorites Stumble It! Digg It!
    www.sajithmr.com

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
Sphere: Related Content

Programming

Leave a Reply


Spam Protection by WP-SpamFree

Droidtip: Install e-mailed .apk files via tAttachApkInstaller

Ever received an .apk attachment via gmail?  As an application reviewer, I most certainly have. For the longest I’ve wished...

Protect your Android Device with Stealth Guards. For Free.

Here’s a limited time offer all you Android phone owners should jump on quickly. StealthGaurds.com is offering its...

TweetDeck for Android is Arriving and its Amazing!

If there’s one area that has no clear winner yet for Android, its Twitter apps.  We have seen apps...

Nexus One Revived as Next Android Developers Phone

In the (not so) recent news, Google announced the discontinuation of the Nexus One.  For many Android fans, this...

Android Development Made Simpler with Droid-fu

android,progrmaming When you program for Android you find yourself doing some of the same tasks repeatedly. As a programmer you know...