保存字符串的共享preferences一个ArrayList字符串、preferences、ArrayList

2023-09-13 01:05:10 作者:心软脾气硬

什么是的ArrayList 字符串保存到共享preferences 在API级别8的最佳方法?我现在能想到的唯一的办法就是保存所有的字符串到分隔的一个字符串用逗号和保存这种方式。但我不知道是否有字符串的最大尺寸。

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(); }

INTERAL存储文件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();