Android SharedPreferences工具类

最近因为需要将List集合和Map集合的数据保存到SharedPreferences中,所以对以前自己封装的SharedPreferencesUtil进行了修改,在原有的保存读Integer,String,Float,Long,Boolean,Object的基础上增加了保存读取List以及Map<String,Object>的功能。话不多说,下面直接贴代码和简单的Demo,仅供参考:

SharedPreferencesUtil

public class SharedPreferencesUtil {

private static SharedPreferencesUtil util;
private static SharedPreferences sp;

private SharedPreferencesUtil(Context context, String name) {
    sp = context.getSharedPreferences(name, Context.MODE_PRIVATE);
}

/**
 * 初始化SharedPreferencesUtil,只需要初始化一次,建议在Application中初始化
 *
 * @param context 上下文对象
 * @param name    SharedPreferences Name
 */
public static void getInstance(Context context, String name) {
    if (util == null) {
        util = new SharedPreferencesUtil(context, name);
    }
}

/**
 * 保存数据到SharedPreferences
 *
 * @param key   键
 * @param value 需要保存的数据
 * @return 保存结果
 */
public static boolean putData(String key, Object value) {
    boolean result;
    SharedPreferences.Editor editor = sp.edit();
    String type = value.getClass().getSimpleName();
    try {
        switch (type) {
            case "Boolean":
                editor.putBoolean(key, (Boolean) value);
                break;
            case "Long":
                editor.putLong(key, (Long) value);
                break;
            case "Float":
                editor.putFloat(key, (Float) value);
                break;
            case "String":
                editor.putString(key, (String) value);
                break;
            case "Integer":
                editor.putInt(key, (Integer) value);
                break;
            default:
                Gson gson = new Gson();
                String json = gson.toJson(value);
                editor.putString(key, json);
                break;
        }
        result = true;
    } catch (Exception e) {
        result = false;
        e.printStackTrace();
    }
    editor.apply();
    return result;
}

/**
 * 获取SharedPreferences中保存的数据
 *
 * @param key          键
 * @param defaultValue 获取失败默认值
 * @return 从SharedPreferences读取的数据
 */
public static Object getData(String key, Object defaultValue) {
    Object result;
    String type = defaultValue.getClass().getSimpleName();
    try {
        switch (type) {
            case "Boolean":
                result = sp.getBoolean(key, (Boolean) defaultValue);
                break;
            case "Long":
                result = sp.getLong(key, (Long) defaultValue);
                break;
            case "Float":
                result = sp.getFloat(key, (Float) defaultValue);
                break;
            case "String":
                result = sp.getString(key, (String) defaultValue);
                break;
            case "Integer":
                result = sp.getInt(key, (Integer) defaultValue);
                break;
            default:
                Gson gson = new Gson();
                String json = sp.getString(key, "");
                if (!json.equals("") && json.length() > 0) {
                    result = gson.fromJson(json, defaultValue.getClass());
                } else {
                    result = defaultValue;
                }
                break;
        }
    } catch (Exception e) {
        result = null;
        e.printStackTrace();
    }
    return result;
}

/**
 * 用于保存集合
 *
 * @param key  key
 * @param list 集合数据
 * @return 保存结果
 */
public static <T> boolean putListData(String key, List<T> list) {
    boolean result;
    String type = list.get(0).getClass().getSimpleName();
    SharedPreferences.Editor editor = sp.edit();
    JsonArray array = new JsonArray();
    try {
        switch (type) {
            case "Boolean":
                for (int i = 0; i < list.size(); i++) {
                    array.add((Boolean) list.get(i));
                }
                break;
            case "Long":
                for (int i = 0; i < list.size(); i++) {
                    array.add((Long) list.get(i));
                }
                break;
            case "Float":
                for (int i = 0; i < list.size(); i++) {
                    array.add((Float) list.get(i));
                }
                break;
            case "String":
                for (int i = 0; i < list.size(); i++) {
                    array.add((String) list.get(i));
                }
                break;
            case "Integer":
                for (int i = 0; i < list.size(); i++) {
                    array.add((Integer) list.get(i));
                }
                break;
            default:
                Gson gson = new Gson();
                for (int i = 0; i < list.size(); i++) {
                    JsonElement obj = gson.toJsonTree(list.get(i));
                    array.add(obj);
                }
                break;
        }
        editor.putString(key, array.toString());
        result = true;
    } catch (Exception e) {
        result = false;
        e.printStackTrace();
    }
    editor.apply();
    return result;
}

/**
 * 获取保存的List
 *
 * @param key key
 * @return 对应的Lis集合
 */
public static <T> List<T> getListData(String key, Class<T> cls) {
    List<T> list = new ArrayList<>();
    String json = sp.getString(key, "");
    if (!json.equals("") && json.length() > 0) {
        Gson gson = new Gson();
        JsonArray array = new JsonParser().parse(json).getAsJsonArray();
        for (JsonElement elem : array) {
            list.add(gson.fromJson(elem, cls));
        }
    }
    return list;
}

/**
 * 用于保存集合
 *
 * @param key key
 * @param map map数据
 * @return 保存结果
 */
public static <K, V> boolean putHashMapData(String key, Map<K, V> map) {
    boolean result;
    SharedPreferences.Editor editor = sp.edit();
    try {
        Gson gson = new Gson();
        String json = gson.toJson(map);
        editor.putString(key, json);
        result = true;
    } catch (Exception e) {
        result = false;
        e.printStackTrace();
    }
    editor.apply();
    return result;
}

/**
 * 用于保存集合
 *
 * @param key key
 * @return HashMap
 */
public static <V> HashMap<String, V> getHashMapData(String key, Class<V> clsV) {
    String json = sp.getString(key, "");
    HashMap<String, V> map = new HashMap<>();
    Gson gson = new Gson();
    JsonObject obj = new JsonParser().parse(json).getAsJsonObject();
    Set<Map.Entry<String, JsonElement>> entrySet = obj.entrySet();
    for (Map.Entry<String, JsonElement> entry : entrySet) {
        String entryKey = entry.getKey();
        JsonObject value = (JsonObject) entry.getValue();
        map.put(entryKey, gson.fromJson(value, clsV));
    }
    Log.e("SharedPreferencesUtil", obj.toString());
    return map;
}

}

SharedPreferences是无法直接保存Object,List集合和Map集合的,需要先将它们转换为字符串,在保存到SharedPreferences中,取得时候再把对应的字符串转为Object,List集合或者Map集合。
我这里的做法是利用Gson将Object,List或者Map转成Json保存到SharedPreferences中,取数据的时候再通过Gson将json数据转成Object,List集合或者Map集合。
————————————————
版权声明:本文为CSDN博主「Black_Hao」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/a512337862/article/details/73633420

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值