问题描述
我的应用程序具有字符串值的列表(每个部分5-20个字符),我必须持久存储。共享preferences在我看来,最合适的,因为它是一个短名单。通常它会是空的,或者只包含几个值。
My app has a list of String values (of some 5-20 characters each), that I have to store persistently. The SharedPreferences seem to me the most appropriate, as it's a short list. Usually it will be empty, or contain just a few values.
我已经看过<一个href="http://stackoverflow.com/questions/6274480/adding-values-from-a-arraylist-to-shared-$p$pference">this问题它要求基本相同,答案是不适合用作StringSet是API级别11,而我瞄准了Android 2.1及以上,这是API 7。
I've already seen this question which asks basically the same, the answer is unsuitable as the StringSet is API level 11, and I'm targeting Android 2.1 and up, which is API 7.
考虑字符串的通常是小列表,使用数据库共矫枉过正似乎对我。使用一个文件来存储,这将是另一种解决办法,但不是那么优雅。我已经考虑创建密钥(如1,2,3,等等),但实际上比使用文件更糟糕 - 特别是当它涉及到回读我的数据。
Considering the usually small list of strings, using a database seems total overkill to me. Using a file to store this would be another solution but not so elegant. I've considered creating keys (like "1", "2", "3", etc) but that's actually worse than using a file - especially when it comes to reading back my data.
无论如何,如果没有其他的作品我会去的文件选项。如果我的想法是不实际使用共享preferences的API LVL 7,我AP preciate听到了。
Anyway if nothing else works I'll have to go for the file option. If my idea is simply not practical using the SharedPreferences for API lvl 7, I'd appreciate to hear that too.
推荐答案
我发现最简单的解决方案来存储和检索共享preferences物品的清单,以系列化/ deserilaize数组复制到/从JSON和存储为一个字符串设定。
I found the easiest solution to store and retrieve a list of items from SharedPreferences is to simply serialize / deserilaize the array into / from JSON and store it into a string setting.
GSON来真的很方便做这件事。
Gson comes really handy doing it.
READ:
SharedPreferences prefs = context.getSharedPreferences("settings", Context.MODE_PRIVATE);
String value = prefs.getString("list", null);
GsonBuilder gsonb = new GsonBuilder();
Gson gson = gsonb.create();
MyObject[] list = gson.fromJson(value, MyObject[].class);
写:
String value = gson.toJson(list);
SharedPreferences prefs = context.getSharedPreferences("settings", Context.MODE_PRIVATE);
Editor e = prefs.edit();
e.putString("list", value);
e.commit();
这篇关于存储列表或设置共享preferences的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!