保存字符串的共享preferences一个ArrayList [英] Save an arraylist of Strings to shared preferences

查看:123
本文介绍了保存字符串的共享preferences一个ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是的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();

这篇关于保存字符串的共享preferences一个ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆