How can I save and get Hashmap in android using below format in SharedPreference
HashMap<String, List<String>> mChildMap = new HashMap<>();
How can I save and get Hashmap in android using below format in SharedPreference
HashMap<String, List<String>> mChildMap = new HashMap<>();
Function to Insert HashMap into SharedPreference
private void insertToSP(HashMap<String, List<String>> jsonMap) {
String jsonString = new Gson().toJson(jsonMap);
SharedPreferences sharedPreferences = getSharedPreferences("HashMap", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("map", jsonString);
editor.apply();
}
Function to read hashMap from SharedPreference
private HashMap<String, List<String>> readFromSP(){
SharedPreferences sharedPreferences = getSharedPreferences("HashMap", MODE_PRIVATE);
String defValue = new Gson().toJson(new HashMap<String, List<String>>());
String json=sharedPreferences.getString("map",defValue);
TypeToken<HashMap<String,List<String>>> token = new TypeToken<HashMap<String,List<String>>>() {};
HashMap<String,List<String>> retrievedMap=new Gson().fromJson(json,token.getType());
return retrievedMap;
}
Add this dependancy in gradle
implementation 'com.google.code.gson:gson:2.6.2'
The easiest way would be to use Google's Gson to save the HashMap as json. Create a Wrapper class for your HashMap with the the getter and setter methods. Refer the below answer.
You can converti Hashmap as json with Gson library and put it as String. Something like this:
String converted = new Gson().toJson(myMap);
SharedPreferences sharedPreferences = getSharedPreferences("mySharedName", Context.MODE_PRIVATE);
sharedPreferences.edit().putString("key",converted).commit();