简体   繁体   English

如何将Stack保存到SharedPreferences?

[英]How save Stack to SharedPreferences?

In my Android app I have a custom stack for Strings which extends Stack . 在我的Android应用程序中,我有一个用于Strings的自定义堆栈,它扩展了Stack I would like to save the stack to Sharedpreferences and also retrieve it from SharedPreferences. 我想将堆栈保存到Sharedpreferences,并从SharedPreferences中检索它。

I know how to convert a stack to an ArrayList but I've read that SharedPreferences only supports sets not lists. 我知道如何将堆栈转换为ArrayList但我已经读过SharedPreferences只支持集合而不是列表。 So how can I save a stack to SP while preserving its order? 那么如何在保留订单的同时将堆栈保存到SP呢? And how can I retrieve it from SharedPreferences and rebuild the stack? 如何从SharedPreferences中检索它并重建堆栈?

I'm really lost as to how to approach this. 我真的迷失了如何处理这个问题。 Any pointers in the right direction are highly appreciated - I'm not asking for code dump answers. 任何正确方向的指针都非常受欢迎 - 我不是要求代码转储答案。

Here is one possible solution, 这是一个可能的解决方案,

You can convert stack to string via serialization and save the string to shared preference 您可以通过序列化将堆栈转换为字符串,并将字符串保存为共享首选项

ByteArrayOutputStream bos = new ByteArrayOutputStream()
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(stack);
oos.flush();
String base64str = Base64.encode(bos.toByteArray(), Base64.DEFAULT);
...

When load string from preference, decode the base64 string to bytes and using ObjectInputStream to deserialize the stack. 从首选项加载字符串时,将base64字符串解码为字节,并使用ObjectInputStream反序列化堆栈。

As per earlier comment: 按照之前的评论:

You will probably have to serialize/deserialize your Stack to a string representation, which can then be stored in the SharedPreferences . 您可能必须将Stack序列化/反序列化为字符串表示形式,然后可以将其存储在SharedPreferences

It might be possible to (ab)use the json format for this, but it does not give any guarantees about the ordering of the individual elements in the result. 有可能(ab)使用json格式,但它不保证结果中各个元素的排序。 It should be easy enough to include the 'position' for every element too though, which you can then use to sort the elements after deserializing. 它应该很容易包含每个元素的“位置”,然后您可以在反序列化后使用它来对元素进行排序。

Alternatively, you can come up with your own structure. 或者,您可以提出自己的结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM