Android 将字符串数组列表保存到共享首选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12150597/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Save an arraylist of Strings to shared preferences
提问by Peter
What is the best way to save an ArrayListof strings to SharedPreferencesin API level 8? The only way i can think of now is to save all of the strings into one string separated by commas and save it that way. But I don't know if there is a maximum size for strings.
将ArrayList字符串保存到SharedPreferencesAPI 级别 8的最佳方法是什么?我现在能想到的唯一方法是将所有字符串保存到一个以逗号分隔的字符串中并以这种方式保存。但我不知道字符串是否有最大大小。
Is there a better way to do this?
有一个更好的方法吗?
采纳答案by Ali
I suggest you to save the arraylist as Internal Storage File in Android. For example for a arraylist named text_lines:
我建议你在 Android 中将 arraylist 保存为内部存储文件。例如,对于名为 的数组列表text_lines:
Internal storage File IO (Writing) :
内部存储文件 IO(写入):
try {
//Modes: MODE_PRIVATE, MODE_WORLD_READABLE, MODE_WORLD_WRITABLE
FileOutputStream output = openFileOutput("lines.txt",MODE_WORLD_READABLE);
DataOutputStream dout = new DataOutputStream(output);
dout.writeInt(text_lines.size()); // Save line count
for(String line : text_lines) // Save lines
dout.writeUTF(line);
dout.flush(); // Flush stream ...
dout.close(); // ... and close.
}
catch (IOException exc) { exc.printStackTrace(); }
Interal storage File IO (Reading) :
内部存储文件 IO(读取):
FileInputStream input = openFileInput("lines.txt"); // Open input stream
DataInputStream din = new DataInputStream(input);
int sz = din.readInt(); // Read line count
for (int i=0;i<sz;i++) { // Read lines
String line = din.readUTF();
text_lines.add(line);
}
din.close();
回答by biegleux
If you can guarantee your Strings in ArrayListdon't contain comma, you can simply use
如果你能保证你的StringsArrayList不包含逗号,你可以简单地使用
List<String> list = new ArrayList<String>();
...
editor.putString(PREF_KEY_STRINGS, TextUtils.join(",", list));
and to read the list
并阅读清单
String serialized = prefs.getString(PREF_KEY_STRINGS, null);
List<String> list = Arrays.asList(TextUtils.split(serialized, ","));
You are limited by the memory of the device. It's good practice to use background thread to read/write shared preferences.
您受到设备内存的限制。使用后台线程来读/写共享首选项是一种很好的做法。
回答by Jay Bobzin
There is a method, putStringSet(), in SharedPreferences.Editor, which you can take advantage of if your strings are a Set. (That is, no duplicates).
有一种方法 , putStringSet()in SharedPreferences.Editor,如果您的字符串是Set. (也就是说,没有重复)。
回答by Balázs édes
If you are using an api (like level 8) where you cant use put/getStringSet(), then this is a possible solution, but this is very expensiveand not flexibleif you want to store bigger lists. I mean creating a map like datastructure for a simple array-like structure creates a huge overhead, if preformance is important.
如果您使用的是API(如8级),你不能使用PUT / getStringSet(),那么这是一个可能的解决方案,但是这是非常昂贵和不灵活,如果要存储大名单。我的意思是,如果性能很重要,为简单的类似数组的结构创建类似数据结构的映射会产生巨大的开销。
To save it:
要保存它:
public static void writeList(Context context, List<String> list, String prefix)
{
SharedPreferences prefs = context.getSharedPreferences("YourApp", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
int size = prefs.getInt(prefix+"_size", 0);
// clear the previous data if exists
for(int i=0; i<size; i++)
editor.remove(prefix+"_"+i);
// write the current list
for(int i=0; i<list.size(); i++)
editor.putString(prefix+"_"+i, list.get(i));
editor.putInt(prefix+"_size", list.size());
editor.commit();
}
To retrieve it:
要检索它:
public static List<String> readList (Context context, String prefix)
{
SharedPreferences prefs = context.getSharedPreferences("YourApp", Context.MODE_PRIVATE);
int size = prefs.getInt(prefix+"_size", 0);
List<String> data = new ArrayList<String>(size);
for(int i=0; i<size; i++)
data.add(prefs.getString(prefix+"_"+i, null));
return data;
}
And to actually use it:
并实际使用它:
List<String> animals = new ArrayList<String>();
animals.add("cat");
animals.add("bear");
animals.add("dog");
writeList(someContext, animals, "animal");
And to retrieve it:
并检索它:
List<String> animals = readList (someContext, "animal");
If you are not limited to use SharedPreferences, consider using SQLiteDatabase!
如果您不限于使用 SharedPreferences,请考虑使用SQLiteDatabase!

![Android dex 加载器无法执行 dex:方法 ID 不在 [0, 0xffff] 中:65536](/res/img/loading.gif)