sr09 sr09 - 2 months ago 7
Android Question

How to store a stack in SharedPreferences

I've been trying to store a stack in SharedPreferences as a set through the

putStringSet
API in
SharedPreferences
.

In the write method, I do this:
putStringSet(KEY, new LinkedHashSet(stack));


When I read, I do this:
getStringSet(KEY, null)
into a
Set
.

I reverse the elements in the set by converting to a list using
Collections.reverse(list)
, and all the elements to the stack.

Things are great when I write into
SharedPreferences
, but the order of elements is completely messed up when I read.

Any ideas?

Answer

You can convert your stack elements to a comma separated String and then use putString to save it.

For example, if your stack contains the following:

| "4" |
| "3" |
| "2" |
| "1" |
| "0" |
-------

You should convert it to the String "0,1,2,3,4" and save it to SharedPreferences.

To rebuild your stack, get the String from the SharedPreferences, split it by the comma separator and push it in order to the stack.