Helping Geeks Win the War on Technology Since 2010

Android: How to Share Data Between Separate Activities

July 7, 2011

Android programming stresses the use of separate activities within a main program–also an activity–to handle interface changes like going from one menu screen to another. The problem arises when you need to share data between seprate activities, like user data entered on a previous screen.

Let’s take a simple example where ActivityA is an activity class that has prompted the user for his or her name. ActivityB is the next screen the user gets taken to which will use that data. The assumption here is that you have declared a string “name” that will store this data.

Put this code anywhere in class ActivityA:

Intent myIntent = new Intent(v.getContext(), ActivityB.class); /* v is a View here */
Bundle myBundle = new Bundle();
myBundle.putString("USER_NAME", name);
myIntent.putExtras(myBundle);
startActivityForResult(myIntent, 0);

What you’ve done is prepared the data so ActivityB can access it.

Put this code anywhere in class ActivityB:

String name = getIntent().getExtras().getString("USER_NAME");

Now ActivityB is able to grab the data that was originally set from ActivityA.

posted in Android by helpgeek

Follow comments via the RSS Feed | Leave a comment | Trackback URL

Leave Your Comment

 
Powered by Wordpress and MySQL on MDDHosting. Theme by Shlomi Noach, openark.org