用SharedPreferences存储集合

来源:互联网 发布:最优化方法第四章答案 编辑:程序博客网 时间:2024/06/04 07:30

思路:参考网上资料,存储json字符串,使用时进行解析即可,为避免重复,建议用set集合


例:

/** * 获得用户登录过的所有账户 * @return 用户名的set集合 */public static HashSet<String> getAccountList() {    SharedPreferences sp=getSharedPreferences();    HashSet<String>set=new HashSet<>();    String json = sp.getString(KEY_USER_ACCOUNTS, "");    try {        JSONArray jsonArray = new JSONArray(json);        for (int i = 0; i < jsonArray.length(); i++) {            set.add(jsonArray.getString(i));        }    } catch (JSONException e) {        e.printStackTrace();    }    return set;}/** * 添加用户账户到sharedPreference中 * @param str 用户账户 */public static void addAccountToList(@NonNull String str){    SharedPreferences sp=getSharedPreferences();    if (str.trim().length()<1) {        return;    }    SharedPreferences.Editor edit = sp.edit();    HashSet<String> spList = getAccountList();    spList.add(str.trim());    JSONArray jsonArray = new JSONArray(spList);    String s = jsonArray.toString();    edit.putString(KEY_USER_ACCOUNTS,s).commit();}