将哈希映射保存到共享首选项中
如何在Android中将哈希表保存到共享首选项 ?
我不build议将复杂对象写入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();
我使用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(); }
我写了一段简单的代码来优先保存地图,并从首选项加载地图。 不需要GSON或Jacksonfunction。 我只使用了一个具有string作为键和布尔值作为值的地图。
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(); Editor editor = pSharedPref.edit(); editor.remove("My_map").commit(); editor.putString("My_map", jsonString); editor.commit(); } } private Map<String,Boolean> loadMap(){ Map<String,Boolean> outputMap = new HashMap<String,Boolean>(); SharedPreferences pSharedPref = getApplicationContext().getSharedPreferences("MyVariables", Context.MODE_PRIVATE); try{ if (pSharedPref != null){ String jsonString = pSharedPref.getString("My_map", (new JSONObject()).toString()); JSONObject jsonObject = new JSONObject(jsonString); Iterator<String> keysItr = jsonObject.keys(); while(keysItr.hasNext()) { String key = keysItr.next(); Boolean value = (Boolean) jsonObject.get(key); outputMap.put(key, value); } } }catch(Exception e){ e.printStackTrace(); } return outputMap; }
Map<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; }
你可以尝试使用JSON。
为了节省
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(); }