Can I use Android's sharedpreferences to pass a Java object between different activities?
Asked
Active
Viewed 684 times
1
-
1Not unless you marshall it, look up Parcleable. – Kristopher Micinski May 10 '12 at 17:08
-
No. There is no work around. You can't pass a pointer. – Kristopher Micinski May 10 '12 at 17:15
-
What are you trying to accomplish? – Santa May 10 '12 at 17:26
-
In my first activity, an object is created. Then I have several next activities. Each uses only a few attributes of that object. – Kalaji May 10 '12 at 17:32
2 Answers
1
"Bundles" are probably the best way to go:
Intent and Bundle are two classes to transfer object's from one activity to another activity. You can create bundle object and put them into intent
If you want to pass an "object" in your Bundle, then the object must implement "Parcelable":
Yet another alternative is to use global state:
0
No. For that purpose I suggest creating an implementation of the Application class as a singleton and keeping a reference to your object there.
Edit after reading comments: Keep in mind though that a singleton has many drawbacks and should be used only if the other solutions are insufficient.

OlivierLi
- 2,798
- 1
- 23
- 30
-
this still probably indicates a borked part of your design. – Kristopher Micinski May 10 '12 at 17:16
-
@Kristopher Micinski : How do you mean? Is your objection with implementing the applications class or the Singleton pattern? – OlivierLi May 10 '12 at 17:37
-
1My objection is that too many people want to keep a singleton when they really don't need it. My objection isn't to your comment. If you think through it and rationalize it then it's an ok solution. But there's a very hasty idea that you can just use a "global variable" to hack your design, when in reality you should be able to compartmentalize this better within the pieces of your app. – Kristopher Micinski May 10 '12 at 17:39
-
I see what you mean. I'm working on and Android application right now and this ended up being the most efficient solution I think. After rereading the question I see now how a singleton might be overkill. I'll add a comment to my answer. Thanks for the input! – OlivierLi May 10 '12 at 17:43
-