0

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?

nrofis
  • 8,975
  • 14
  • 58
  • 113

1 Answers1

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
  • I don't know how much objects do I have (the user decide) – nrofis Apr 16 '13 at 18:19
  • 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
  • Is there any way to use SharedPreferences instead Serialize? – nrofis Apr 16 '13 at 19:27
  • 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