将字符串数组列表保存到共享首选项 [英] Save an arraylist of Strings to shared preferences
问题描述
在 API 级别 8 中将 ArrayList
字符串保存到 SharedPreferences
的最佳方法是什么?我现在能想到的唯一方法是将所有字符串保存到一个以逗号分隔的字符串中并以这种方式保存.但是我不知道字符串是否有最大大小.
What is the best way to save an ArrayList
of strings to SharedPreferences
in 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.
有没有更好的方法来做到这一点?
Is there a better way to do this?
推荐答案
我建议你在 Android 中将 arraylist 保存为内部存储文件.例如,对于名为 text_lines
的数组列表:
I suggest you to save the arraylist as Internal Storage File in Android. For example for a arraylist named text_lines
:
内部存储文件IO(写入):
Internal storage File IO (Writing) :
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(); }
内部存储文件IO(读取):
Interal storage File IO (Reading) :
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();
这篇关于将字符串数组列表保存到共享首选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!