如何将一个HashMap对象保存到Android的Shared Preferences中?
如何将一个HashMap对象保存到Android的Shared Preferences中?
我使用 Gson
将 HashMap
转换为 String
并将其保存到 SharedPrefs
private void hashmaptest()
{
//create test hashmap
HashMap<String, String> testHashMap = new HashMap<String, String>();
testHashMap.put("key1", "value1");
testHashMap.put("key2", "value2");
//convert to string using gson
Gson gson = new Gson();
String hashMapString = gson.toJson(testHashMap);
//save in shared prefs
SharedPreferences prefs = getSharedPreferences("test", MODE_PRIVATE);
prefs.edit().putString("hashString", hashMapString).apply();
//get from shared prefs
String storedHashMapString = prefs.getString("hashString", "oopsDintWork");
java.lang.reflect.Type type = new TypeToken<HashMap<String, String>>(){}.getType();
HashMap<String, String> testHashMap2 = gson.fromJson(storedHashMapString, type);
//use values
String toastString = testHashMap2.get("key1") + " | " + testHashMap2.get("key2");
Toast.makeText(this, toastString, Toast.LENGTH_LONG).show();
}
我不建议将复杂对象写入SharedPreference。相反,我会使用ObjectOutputStream
将其写入内部存储器。
File file = new File(getDir("data", MODE_PRIVATE), "map");
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(file));
outputStream.writeObject(map);
outputStream.flush();
outputStream.close();
private void saveMap(Map<String,Boolean> inputMap) {
SharedPreferences pSharedPref = getApplicationContext().getSharedPreferences("MyVariables", Context.MODE_PRIVATE);
if (pSharedPref != null){
JSONObject jsonObject = new JSONObject(inputMap);
String jsonString = jsonObject.toString();
pSharedPref.edit()
.remove("My_map")
.putString("My_map", jsonString)
.apply();
}
}
private Map<String,Boolean> loadMap() {
Map<String,Boolean> outputMap = new HashMap<>();
SharedPreferences pSharedPref = getApplicationContext().getSharedPreferences("MyVariables", Context.MODE_PRIVATE);
try {
if (pSharedPref != null) {
String jsonString = pSharedPref.getString("My_map", (new JSONObject()).toString());
if (jsonString != null) {
JSONObject jsonObject = new JSONObject(jsonString);
Iterator<String> keysItr = jsonObject.keys();
while (keysItr.hasNext()) {
String key = keysItr.next();
Boolean value = jsonObject.getBoolean(key);
outputMap.put(key, value);
}
}
}
} catch (JSONException e){
e.printStackTrace();
}
return outputMap;
}
getApplicationContext
? - DmitrygetString()
的默认值为什么要这么奇怪而复杂?一个简单的 null 或空字符串不同样可以吗? - SMBiggsMap<String, String> aMap = new HashMap<String, String>();
aMap.put("key1", "val1");
aMap.put("key2", "val2");
aMap.put("Key3", "val3");
SharedPreferences keyValues = getContext().getSharedPreferences("Your_Shared_Prefs"), Context.MODE_PRIVATE);
SharedPreferences.Editor keyValuesEditor = keyValues.edit();
for (String s : aMap.keySet()) {
keyValuesEditor.putString(s, aMap.get(s));
}
keyValuesEditor.commit();
基于Vinoj John Hosan的回答,我修改了答案以允许更通用的插入,基于数据的键,而不是像"My_map"
那样的单个键。
在我的实现中,MyApp
是我的Application
覆盖类,并且MyApp.getInstance()
用于返回context
。
public static final String USERDATA = "MyVariables";
private static void saveMap(String key, Map<String,String> inputMap){
SharedPreferences pSharedPref = MyApp.getInstance().getSharedPreferences(USERDATA, Context.MODE_PRIVATE);
if (pSharedPref != null){
JSONObject jsonObject = new JSONObject(inputMap);
String jsonString = jsonObject.toString();
SharedPreferences.Editor editor = pSharedPref.edit();
editor.remove(key).commit();
editor.putString(key, jsonString);
editor.commit();
}
}
private static Map<String,String> loadMap(String key){
Map<String,String> outputMap = new HashMap<String,String>();
SharedPreferences pSharedPref = MyApp.getInstance().getSharedPreferences(USERDATA, Context.MODE_PRIVATE);
try{
if (pSharedPref != null){
String jsonString = pSharedPref.getString(key, (new JSONObject()).toString());
JSONObject jsonObject = new JSONObject(jsonString);
Iterator<String> keysItr = jsonObject.keys();
while(keysItr.hasNext()) {
String k = keysItr.next();
String v = (String) jsonObject.get(k);
outputMap.put(k,v);
}
}
}catch(Exception e){
e.printStackTrace();
}
return outputMap;
}
Context
实例一样获取它。查看这个stackoverflow问题:是否可能在Android Library Project中获取应用程序的上下文? - Kyle Falconermap -> string
val jsonString: String = Gson().toJson(map)
preferences.edit().putString("KEY_MAP_SAVE", jsonString).apply()
字符串 -> 映射
val jsonString: String = preferences.getString("KEY_MAP_SAVE", JSONObject().toString())
val listType = object : TypeToken<Map<String, String>>() {}.type
return Gson().fromJson(jsonString, listType)
try {
HashMap<Integer, String> hash = new HashMap<>();
JSONArray arr = new JSONArray();
for(Integer index : hash.keySet()) {
JSONObject json = new JSONObject();
json.put("id", index);
json.put("name", hash.get(index));
arr.put(json);
}
getSharedPreferences(INSERT_YOUR_PREF).edit().putString("savedData", arr.toString()).apply();
} catch (JSONException exception) {
// Do something with exception
}
获取方式:
try {
String data = getSharedPreferences(INSERT_YOUR_PREF).getString("savedData");
HashMap<Integer, String> hash = new HashMap<>();
JSONArray arr = new JSONArray(data);
for(int i = 0; i < arr.length(); i++) {
JSONObject json = arr.getJSONObject(i);
hash.put(json.getInt("id"), json.getString("name"));
}
} catch (Exception e) {
e.printStackTrace();
}
getAll
自API级别1添加 Map getAll() 从首选项中检索所有值。
请注意,您不得修改此方法返回的集合或更改其任何内容。如果您这样做,存储数据的一致性无法保证。
返回Map 返回包含表示首选项的键/值对列表的映射。
对于仅包含不超过几十个元素的狭窄用例,您可以利用SharedPreferences基本上像映射一样工作的事实,并简单地将每个条目存储在自己的键下:
Map<String, String> map = new HashMap<String, String>();
map.put("color", "red");
map.put("type", "fruit");
map.put("name", "Dinsdale");
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
// OR use a specific pref name
// context.getSharedPreferences("myMegaMap");
for (Map.Entry<String, String> entry : map.entrySet()) {
prefs.edit().putString(entry.getKey(), entry.getValue());
}
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
// OR use a specific pref name
// context.getSharedPreferences("myMegaMap");
prefs.getString("color", "pampa");
如果您使用自定义的首选项名称(即context.getSharedPreferences("myMegaMap")
),您也可以使用prefs.getAll()
获取所有键。
您的值可以是SharedPreferences支持的任何类型:
String
,int
,long
,float
,boolean
。
String converted = new Gson().toJson(map);
SharedPreferences sharedPreferences = getSharedPreferences("sharepref",Context.MODE_PRIVATE);
sharedPreferences.edit().putString("yourkey",converted).commit();