Hey,
I’m gonna show you how to save and get HashMap into SharedPreference. It is the same logic as How to save and get ArrayList into SharedPreference.
Markdown:
/**
* Save and get HashMap in SharedPreference
*/
public void saveHashMap(String key , Object obj) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
SharedPreferences.Editor editor = prefs.edit();
Gson gson = new Gson();
String json = gson.toJson(obj);
editor.putString(key,json);
editor.apply(); // This line is IMPORTANT !!!
}
public HashMap<Integer,YourObject> getHashMap(String key) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
Gson gson = new Gson();
String json = prefs.getString(key,"");
java.lang.reflect.Type type = new TypeToken<HashMap<Integer,YourObject>>(){}.getType();
HashMap<Integer,YourObject> obj = gson.fromJson(json, type);
return obj;
}
Gist:
/** * Save and get HashMap in SharedPreference */ public void saveHashMap(String key , Object obj) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity); SharedPreferences.Editor editor = prefs.edit(); Gson gson = new Gson(); String json = gson.toJson(obj); editor.putString(key,json); editor.apply(); // This line is IMPORTANT !!! } public HashMap<Integer,YourObject> getHashMap(String key) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity); Gson gson = new Gson(); String json = prefs.getString(key,""); java.lang.reflect.Type type = new TypeToken<HashMap<Integer,YourObject>>(){}.getType(); HashMap<Integer,YourObject> obj = gson.fromJson(json, type); return obj; }First of all, we can use this save method as many as we need. You just need to change the key and save it into the SharedPreference.You just need to be careful about your HashMap’s types. I just use “Integer, Object” as an example. You can change it and use your own Object, or even use String, Double etc. It’s all up to your need.Do not forget to change your own HashMap type while using it :)If you have a question, ask me :)