There's a good example here.
So if your Map is like so:
HashMap<String, byte[]> = new HashMap<>();
The functions look like this:
public void saveHashMap(String key , Object obj) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
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<String,byte[]> getHashMap(String key) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Gson gson = new Gson();
String json = prefs.getString(key,"");
java.lang.reflect.Type type = new TypeToken<HashMap<String,byte[]>>(){}.getType();
HashMap<String,byte[]> obj = gson.fromJson(json, type);
return obj;
}
The Generic code looks like this:
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;
}
Replace YourObject
with, well, your Java object.