Android存储:sharedpreferences存储一个Map
程序员文章站
2022-09-30 14:41:04
最近突然项目中用到的sharedpreferences来存储一个Map集合,特来此记录一下可以让更多的小伙伴知道一下。
这里只是一个记录单独存储map的,可以直接用
Strin...
最近突然项目中用到的sharedpreferences来存储一个Map集合,特来此记录一下可以让更多的小伙伴知道一下。
这里只是一个记录单独存储map的,可以直接用
String?examtype = "examtype";
//存储Map
public static void setMap(Context context, Map map) { if (map != null) { JSONStringer jsonStringer = new JSONStringer(); try { jsonStringer.array(); for (String string : map.keySet()) { jsonStringer.object(); jsonStringer.key("year"); jsonStringer.value(string); jsonStringer.key("month"); jsonStringer.value(map.get(string)); jsonStringer.endObject(); } jsonStringer.endArray(); } catch (JSONException e) { e.printStackTrace(); } SharedPreferences sp = context.getSharedPreferences("map", Context.MODE_PRIVATE); sp.edit().putString(examtype, jsonStringer.toString()).apply(); } }
//获取Map的值
public static Map getMap(Context context) { Map examMap = new HashMap<>(); SharedPreferences sp = context.getSharedPreferences("map", Context.MODE_PRIVATE); String map = sp.getString(examtype, ""); if (map.length() > 0) { JSONTokener jsonTokener = new JSONTokener(map); try { JSONArray jsonArray = (JSONArray) jsonTokener.nextValue(); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); examMap.put(jsonObject.getString("year"), jsonObject.getString("month")); } } catch (JSONException e) { e.printStackTrace(); } } return examMap; }
上一篇: 悲了个催的,他们都是有故事的人