原文地址:http://doublekj.blog.163.com/blog/static/146818474201322944643761/
1.Android3.0之后,SharedPreferences提供了putStringSet方法,可以保存字符串数组,例子:
SharedPreferences sp = mContext.getSharedPreferences(“data”, Context.MODE_PRIVATE);
Editor et = sp.edit();
Set set = new HashSet();
set.add(“hello”);
et.putStringSet(key, set);
2.但需要注意的是,Set中不允许重复元素,若有重复元素,它会自动删除。不满足我的需求,所以这里采取这样的方式存放字符串数组:
构建两个函数,用于读取和存放 字符串数组
public String[] getSharedPreference(String key) {
String regularEx = “#”;
String[] str = null;
SharedPreferences sp = mContext.getSharedPreferences(“data”, Context.MODE_PRIVATE);
String values;
values = sp.getString(key, “”);
str = values.split(regularEx);
return str;
}
public void setSharedPreference(String key, String[] values) {
String regularEx = “#”;
String str = “”;
SharedPreferences sp = mContext.getSharedPreferences(“data”, Context.MODE_PRIVATE);
if (values != null && values.length > 0) {
for (String value : values) {
str += value;
str += regularEx;
}
Editor et = sp.edit();
et.putString(key, str);
et.commit();
}
}