views:

1289

answers:

6

I need to be able to use one object in multiple activities within my app, and it needs to be the SAME object. What is the best way to do this?

I have tried making the object "public static" so it can be accessed by other activities but for some reason this just isn't cutting it. Are there any other ways of doing this?

+6  A: 

You can create a subclass of Application and store your shared object there. The Application object should exist for the lifetime of your app as long as there is some active component.

From your activities, you can access the application object via getApplication().

Erich Douglass
Ok this is new to me. how would i implement that?
mtmurdock
What i ended up actually doing was making the object a protected member of my startup activity and then referenced the variable from other activities directly. This isn't exactly Erich's answer but it was his answer that gave me the idea
mtmurdock
+2  A: 

It depends on the type of data you need access to. If you have some kind of data pool that needs to persist across Activitys then Erich's answer is the way to go. If you just need to pass a few objects from one activity to another then you can have them implement Serializable and pass them in the extras of the Intent to start the new Activity.

CaseyB
+1  A: 

Your object can also implement Parcelable interface. Then you can use Bundle.putParcelable() method and pass your object between activities within intent. Photostream application uses this approach and may be used as a reference http://code.google.com/p/apps-for-android/.

Fedor
+1  A: 

The Dev guide FAQ section on developer.android.com has a very good summary of recommendations for this

Sam Svenbjorgchristiensensen
A: 

You can achieve this by using Intent and Bundle class putExtra Methods For more details please see http://bimbim.in/post/2010/09/27/Android-Passing-object-from-one-activity-to-another.aspx

bimbim.in
A: 

Maybe it's an unpopular answer, but in the past I've simply used a class that has a static reference to the object I want to persist through activities. So,

public class PersonHelper
{
    public static Person person;
}

I tried going down the Parcelable interface path, but ran into a number of issues with it and the overhead in your code was unappealing to me.

Chris Stewart