Android的共享preferences和阵列阵列、Android、preferences

2023-09-06 05:57:18 作者:誓言再美丶抵不过流年似水

我创建了一个天气小部件。我保存它的配置共享preferences 。该插件由服务更新。我在一个阵列的预测保持在一起的气象信息。之后,手机关机,晚上我发现数组值都走了,也许是系统挂起?服务。有没有一种方法来存储在分享preferences阵列所以它是比较粘。

I created a weather widget. I store its configuration in SharedPreferences. The widget is updated by a service. I keep the weather information together with forecasts in an array. After the phone is off for the night i find that the array values are gone,maybe the system suspended? the service. Is there a way to store the array in SharePreferences so it is more sticky.

推荐答案

当然 - 要么想出一个办法序列化/从您可以在共享preference存储字符串反序列化对象(如果它是一个简单阵列的数字,比如,仅仅做一个快速的分割/结合的逗号可能做到这一点;基本的 JSON序列 /反序列化可能对稍微复杂的数据),或者使用标准的 Java序列化把你的对象转换为字节流和的数据保存到一个文件在需要的时候,你可以阅读。如果你真的在使用大量的结构化数据,但是,认真考虑使用Android的优异内置的SQLite的支持,虽然这是一个多一点的工作。

Sure - either come up with a way to serialize/deserialize your object from a String that you can store in a SharedPreference (if it's a simple array of numbers, for instance, just making a quick split/join on commas might do it; basic JSON serialization/deserialization might work for slightly more complex data), or use standard Java serialization to turn your object into a bytestream and save the data to a File that you can read when needed. If you're really working with a lot of structured data, though, seriously consider using Android's excellent built-in support for SQLite, although that's a little more work.