Is there any way to save preferences per complex objects?
I have a dynamic list of objects that each contains 3 strings and 2 dynamic lists of pair of booleans. Is there any way to save those objects like preferences?
Asked
Active
Viewed 465 times
0

nrofis
- 8,975
- 14
- 58
- 113
-
What have you considered? Refer to Android documentation on storage options. – Phil Apr 16 '13 at 16:36
-
I did something similar by doing everything to JSON to string and then storing in prefs. – Fahad Ishaque Apr 16 '13 at 16:37
-
I just ask if it possible to save preferences per objects in android – nrofis Apr 16 '13 at 17:13
1 Answers
0
You have the option to serialize your complex objects to a file. Then deserialize to recreate the object back from the file. This is not much different from saving to SharedPreferences.
You can refer the code here. https://stackoverflow.com/a/5816861/2107118
Note: Do make your complex object implement Serializable interface and provide a serialVersionUID.

Community
- 1
- 1

appsroxcom
- 2,821
- 13
- 17
-
-
That shouldn't be a problem. You just need to give a unique name to the file. It is almost similar to SharedPreferences.edit().put methods which take a key. In this case the key is the file name. – appsroxcom Apr 16 '13 at 18:28
-
-
SharedPreferences doesn't support complex objects. You may try to convert the object to JSON or XML and then put it as a string in the preferences. But that is what serialization is doing for you. – appsroxcom Apr 16 '13 at 19:31
-
But how the SharedPreferences will know that the same name of property belongs to different objects? – nrofis Apr 17 '13 at 08:16
-
Right .. think of SharedPreferences as a HashMap. You need to have separate names for different objects. You cannot use the same name of the property for different objects. The name is kind of pointer to a particular object and you cannot point to different objects at the same time with a single name. – appsroxcom Apr 17 '13 at 09:14