android2.3如何使用SharedPreferences儲存字串集合類型的元素

來源:互聯網
上載者:User

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

上面代碼親測了

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.