SharedPreferences 保存复杂数据结构

    技术2023-07-25  86

    保存基本数据类型

    /** * 保存数据到SharedPreferences * * @param key 键 * @param value 需要保存的数据 * @return 保存结果 */ public static boolean putData(String key, Object value) { boolean result; SharedPreferences.Editor editor = getPreference(ContextUtils.get()).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(); SharedPreferences sp = getPreference(ContextUtils.get()); 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 = getPreference(ContextUtils.get()).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 = getPreference(ContextUtils.get()).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; }

    保存Hashmap

    public static void putHashMapData(String key, Map<String, Integer> datas) { JSONArray mJsonArray = new JSONArray(); Iterator<Map.Entry<String, Integer>> iterator = datas.entrySet().iterator(); JSONObject object = new JSONObject(); while (iterator.hasNext()) { Map.Entry<String, Integer> entry = iterator.next(); try { object.put(entry.getKey(), entry.getValue()); } catch (JSONException e) { } } mJsonArray.put(object); SharedPreferences.Editor editor = getPreference(ContextUtils.get()).edit(); editor.putString(key, mJsonArray.toString()); editor.commit(); } public static HashMap<String, Integer> getHashMapData(String key) { HashMap<String, Integer> datas = new HashMap<>(); SharedPreferences sp = getPreference(ContextUtils.get()); String result = sp.getString(key, ""); YxLog.d(TAG, "getHashMapData --- result = " + result); try { JSONArray array = new JSONArray(result); YxLog.d(TAG, "getHashMapData --- array.length() = " + array.length()); for (int i = 0; i < array.length(); i++) { JSONObject itemObject = array.getJSONObject(i); JSONArray names = itemObject.names(); if (names != null) { YxLog.d(TAG, "getHashMapData --- names.length() = " + names.length()); for (int j = 0; j < names.length(); j++) { String name = names.getString(j); Integer value = itemObject.getInt(name); datas.put(name, value); } } } } catch (JSONException e) { YxLog.e(TAG, "getHashMapData --- err = " + e.getMessage()); } return datas; }

    读取json文件列表

    /** * 从asset获取json字符串 * * @param fileName * @return */ public static String getJsonfromAsset(String fileName) { YxLog.d(TAG, "getJson --- fileName = " + fileName); StringBuilder stringBuilder = new StringBuilder(); try { AssetManager assetManager = ContextUtils.get().getAssets(); BufferedReader bf = new BufferedReader(new InputStreamReader(assetManager.open(fileName))); String line; while ((line = bf.readLine()) != null) { stringBuilder.append(line); // YxLog.d(TAG, line); } } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } YxLog.d(TAG, "getJson --- stringBuilder.toString() = \n" + stringBuilder.toString()); return stringBuilder.toString(); } /** * 字符串获取列表 * @param jsonString * @param classOfT * @param <T> * @return */ public static <T> ArrayList<T> getDataListFromString(String jsonString, Class<T> classOfT, Type type) { YxLog.d(TAG, "getDataListFromString --- jsonString = " + jsonString); ArrayList<T> dataList = null; if ((jsonString == null) || (jsonString.trim().length() == 0)) { YxLog.e(TAG, "getDataListFromString --- jsonString is null or size is 0."); return dataList; } Gson gson = new Gson(); try { // json -->对象 dataList = gson.fromJson(jsonString, type); } catch (JsonSyntaxException e) { YxLog.e(TAG, "getDataListFromString --- err: " + e.getMessage()); e.printStackTrace(); } catch (Exception e) { YxLog.e(TAG, "getDataListFromString --- err: " + e.getMessage()); e.printStackTrace(); } return dataList; }
    Processed: 0.009, SQL: 9