<分区>
如何在 Android 中使用以下格式在 SharedPreference 中保存和获取 Hashmap
HashMap<String, List<String>> mChildMap = new HashMap<>();
<分区>
如何在 Android 中使用以下格式在 SharedPreference 中保存和获取 Hashmap
HashMap<String, List<String>> mChildMap = new HashMap<>();
最佳答案
将HashMap插入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();
}
从SharedPreference中读取hashMap的函数
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;
}
在gradle中添加这个依赖
implementation 'com.google.code.gson:gson:2.6.2'
关于java - 将 HashMap 保存到 SharedPreferences,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39204258/