Save Map in SharePreferences of Android storage

As we all know, SharePreferences is a lightweight storage class in Andrade, which can store string and other types of data. However, many students may not know how to save a Map through SP. here is a brief introduction

Scenario: work needs to save a map dynamically. Each time you need to query whether there is an element, if there is one, it will not be saved. If not, it will be saved
//Take out the stored map

public static Map<String, String> getMap(Context context) {
    Map<String, String> defaultMonthMap = new HashMap<>();
    SharedPreferences sp = context.getSharedPreferences("map", Context.MODE_PRIVATE);
    String year2month = sp.getString(defaultMonth, "");
    if (year2month.length() > 0) {
        JSONTokener jsonTokener = new JSONTokener(year2month);
        try {
            JSONArray jsonArray = (JSONArray) jsonTokener.nextValue();
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                defaultMonthMap.put(jsonObject.getString("year"), jsonObject.getString("month"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    return defaultMonthMap;
}

//Save map

public static void setMap(Context context, Map<String, String> year2monthMap) {
    if (year2monthMap != null) {
        JSONStringer jsonStringer = new JSONStringer();
        try {
            jsonStringer.array();
            for (String string : year2monthMap.keySet()) {
                jsonStringer.object();
                jsonStringer.key("year");
                jsonStringer.value(string);
                jsonStringer.key("month");
                jsonStringer.value(year2monthMap.get(string));
                jsonStringer.endObject();
            }
            jsonStringer.endArray();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        SharedPreferences sp = context.getSharedPreferences("map", Context.MODE_PRIVATE);
        sp.edit().putString(defaultMonth, jsonStringer.toString()).apply();
    }
}

Where defaultMonth is the key defined by itself

Posted on Sun, 03 May 2020 15:05:35 -0700 by Capnstank