sr09 sr09 - 1 month ago 5x
Android Question

How to store a stack in SharedPreferences

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

API in

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

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

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

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

Any ideas?


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.