I have an ArrayList
of objects that have a name and an icon pointer and I want to save it in SharedPreferences
. How can I do?
NOTE:
When I was bugged with this, I got the serializing solution where, you can serialize your string, But I came up with a hack as well.
Read this only if you haven't read about serializing, else go down and read my hack
In order to store array items in order, we can serialize the array into a single string (by making a new class ObjectSerializer (copy the code from – www.androiddevcourse.com/objectserializer.html , replace everything except the package name))
Entering data in Shared preference :
the rest of the code on line 38 -
Put the next arg as this, so that if data is not retrieved it will return empty array(we cant put empty string coz the container/variable is an array not string)
Coming to my Hack :-
Merge contents of array into a single string by having some symbol in between each item and then split it using that symbol when retrieving it. Coz adding and retrieving String is easy with shared preferences. If you are worried about splitting just look up "splitting a string in java".
[Note: This works fine if the contents of your array is of primitive kind like string, int, float, etc. It will work for complex arrays which have its own structure, suppose a phone book, but the merging and splitting would become a bit complex. ]
PS: I am new to android, so don't know if it is a good hack, so lemme know if you find better hacks.