Android3.0以上版本中 SharedPreferences新增了函数
abstract Set<String> getStringSet(String key, Set<String> defValues) Retrieve a set of String values from the preferences.
同时SharedPreferences.Editor中也新增了函数
abstract SharedPreferences.Editor putStringSet(String key, Set<String> values) Set a set of String values in the preferences editor, to be written back once commit() is called.
这样可以直接存储一个字符串集合,但是android3.0以前的版本中没有,如何在android2.3的系统中寻找一种替代他们的方式,我们可以猜想下上面两个函数的实现,直接看代码:
public class SharedPreferencesHandler { final static String regularEx = "|"; public static Set<String> getStringSet(SharedPreferences prefs, String key, Set<String> defValues) { String str = prefs.getString(key, ""); if (!str.isEmpty()) { String[] values = str.split(regularEx); if (defValues == null) { defValues = new HashSet<String>(); for (String value : values) { if (!value.isEmpty()) { defValues.add(value); } } } } return defValues; } public static SharedPreferences.Editor putStringSet( SharedPreferences.Editor ed, String key, Set<String> values) { String str = ""; if (values != null | !values.isEmpty()) { Object[] objects = values.toArray(); for (Object obj : objects) { str += obj.toString(); str += regularEx; } ed.putString(key, str); } return ed; } }
然后使用的时候可以这样存储和获取一个字符串的集合:
final Set<String> snoozedIds = SharedPreferencesHandler .getStringSet(prefs, PREF_SNOOZE_IDS, new HashSet<String>()); // prefs.getStringSet(PREF_SNOOZE_IDS, // new HashSet<String>()); snoozedIds.add(Integer.toString(id)); final SharedPreferences.Editor ed = prefs.edit(); SharedPreferencesHandler.putStringSet(ed, PREF_SNOOZE_IDS, snoozedIds); // ed.putStringSet(PREF_SNOOZE_IDS, snoozedIds); ed.putLong(getAirPrefSnoozeTimeKey(id), time); ed.apply();
上面代码亲测了