How to save HashMap to Shared Preferences?
I would not recommend writing complex objects into SharedPreference. Instead I would use ObjectOutputStream
to write it to the internal memory.
File file = new File(getDir("data", MODE_PRIVATE), "map"); ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(file));outputStream.writeObject(map);outputStream.flush();outputStream.close();
I use Gson
to convert HashMap
to String
and then save it to SharedPrefs
private void hashmaptest(){ //create test hashmap HashMap<String, String> testHashMap = new HashMap<String, String>(); testHashMap.put("key1", "value1"); testHashMap.put("key2", "value2"); //convert to string using gson Gson gson = new Gson(); String hashMapString = gson.toJson(testHashMap); //save in shared prefs SharedPreferences prefs = getSharedPreferences("test", MODE_PRIVATE); prefs.edit().putString("hashString", hashMapString).apply(); //get from shared prefs String storedHashMapString = prefs.getString("hashString", "oopsDintWork"); java.lang.reflect.Type type = new TypeToken<HashMap<String, String>>(){}.getType(); HashMap<String, String> testHashMap2 = gson.fromJson(storedHashMapString, type); //use values String toastString = testHashMap2.get("key1") + " | " + testHashMap2.get("key2"); Toast.makeText(this, toastString, Toast.LENGTH_LONG).show();}
private void saveMap(Map<String,Boolean> inputMap) { SharedPreferences pSharedPref = getApplicationContext().getSharedPreferences("MyVariables", Context.MODE_PRIVATE); if (pSharedPref != null){ JSONObject jsonObject = new JSONObject(inputMap); String jsonString = jsonObject.toString(); pSharedPref.edit() .remove("My_map") .putString("My_map", jsonString) .apply(); }}private Map<String,Boolean> loadMap() { Map<String,Boolean> outputMap = new HashMap<>(); SharedPreferences pSharedPref = getApplicationContext().getSharedPreferences("MyVariables", Context.MODE_PRIVATE); try { if (pSharedPref != null) { String jsonString = pSharedPref.getString("My_map", (new JSONObject()).toString()); if (jsonString != null) { JSONObject jsonObject = new JSONObject(jsonString); Iterator<String> keysItr = jsonObject.keys(); while (keysItr.hasNext()) { String key = keysItr.next(); Boolean value = jsonObject.getBoolean(key); outputMap.put(key, value); } } } } catch (JSONException e){ e.printStackTrace(); } return outputMap;}