日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

[原]android2.3如何使用SharedPreferences存储字符串集合类型的元素

發布時間:2025/7/25 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [原]android2.3如何使用SharedPreferences存储字符串集合类型的元素 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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



上面代碼親測了


作者:wjh200821 發表于2012-3-15 19:32:05 原文鏈接 閱讀:47 評論:0 查看評論

轉載于:https://www.cnblogs.com/tilltheendwjx/archive/2012/03/15/2477532.html

總結

以上是生活随笔為你收集整理的[原]android2.3如何使用SharedPreferences存储字符串集合类型的元素的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。