有一个很好的例子here。
如果你的地图是这样的:
HashMap<String, byte[]> = new HashMap<>();
函数如下所示:
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;
}
通用代码如下所示:
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;
}
用您的 Java 对象替换 YourObject。