3

How can I save and get Hashmap in android using below format in SharedPreference

HashMap<String, List<String>> mChildMap = new HashMap<>();    
Jinesh Francis
  • 3,377
  • 3
  • 22
  • 37
Ramkumar.M
  • 681
  • 6
  • 21

3 Answers3

7

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'
Jinesh Francis
  • 3,377
  • 3
  • 22
  • 37
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.

https://stackoverflow.com/a/11931812/5425930

Community
  • 1
  • 1
1

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();
an_droid_dev
  • 1,136
  • 14
  • 18