Is it possible to add an array or object to SharedPreferences on Android

前端 未结 11 1611
别跟我提以往
别跟我提以往 2020-11-22 11:27

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:

11条回答
  •  清酒与你
    2020-11-22 11:44

    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.

提交回复
热议问题