2011-10-30 34 views

回答

69

我不會推薦將複雜對象寫入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(); 
+2

以後如何讀這個'HashMap'? – Roman

+5

使用ObjectInputStream。 –

+1

這個答案是最有幫助的! – mxg

29
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(); 
+0

但我需要的哈希地圖保存爲本身就像我們添加矢量到共享偏好 – jibysthomas

+0

比你有可能使用序列化和保存在SharedPrefs中序列化HashMap。您可以輕鬆找到有關如何執行此操作的代碼示例。 – hovanessyan

41

我使用GsonHashMap轉換爲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(); 
} 
+3

但我們該怎麼做?任何代碼示例? –

+0

如何從GSON獲得的HashMap我有錯誤味精一樣com.qb.gson.JsonSyntaxException:java.lang.IllegalStateException:預期BEGIN_OBJECT但行1列2 BEGIN_ARRAY - – Ram

+0

@Ram我添加的代碼。也許這會幫助 – penduDev

31

我已經寫了一段簡單的代碼來保存地圖優先並加載從偏好地圖。不需要GSON或Jackson功能。我剛剛使用了一個具有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; 
} 
2

您可以嘗試使用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(); 
} 
6

作爲分拆Vinoj約翰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; 
} 
0

可以在專用的使用共享Prefs文件(來源:https://developer.android.com/reference/android/content/SharedPreferences.html):

GETALL

在API級別1地圖GETALL加入()從 所述檢索的所有值優先。

請注意,您不得修改此方法返回的集合, 或更改其任何內容。您保存的數據的一致性是 ,如果您這樣做,則無法保證。

返回地圖返回包含表對偏好的鍵/值的列表 的地圖。