2013-06-20 50 views
1

我有一個已在活動中生成的HashMap,我想使用類似於SharedPreferences的東西來存儲它。我試圖找到信息並引用了一些名爲GSON的東西,但我不確定那是什麼。如果我有這樣的:想要存儲一個HashMap?

HashMap<String, String> hashMap = new HashMap<String, String>(); 
hashMap.put("String 1", "Value 1"); 
hashMap.put("String 2", "Value 2"); 

我怎麼能存儲hashMap,這樣我可以然後在另一個活動閱讀和使用這些信息?如果用戶關閉應用程序,它也需要存儲。

+0

http://stackoverflow.com/questions/9227016/how-to-store-hashmap-on-android –

+0

如果它是一個很大的散列圖,也許你想存儲在一個分區 – lelloman

回答

2

Json與HasMap非常相似。要保存一個JSON你必須使用一個鍵和值像HasMap:

JSONObject userDetail = new JSONObject(); 

     userDetail.put("email", email); 
     userDetail.put("token", token); 

之後,你可以使用一個FileWriter或的FileInputStream將其保存在文件上傳.json,您可以從使用JSONParser其他activitys得到它。

有關JSON的更多信息看this

1

轉到維克多的答案。

但是,如果你的HashMap是複雜的,就像(內部哈希散列散列) 你可以在一個文件直接存儲,後來閱讀:

寫入文件:

public void saveHashToFile(HashMap<String, Object> hash) throws IOException{ 
     String filePath = getApplicationContext().getFilesDir().getPath().toString() + "/your.properties"; 
     File file = new File(filePath); 
     FileOutputStream f = new FileOutputStream(file); 
     ObjectOutputStream s = new ObjectOutputStream(f); 
     s.writeObject(getProperty_Global()); 
     s.close(); 


    } 

回讀從文件:

 public HashMap<String, Object> getLocalHashFromFile() throws OptionalDataException, ClassNotFoundException, IOException{ 

     String filePath = getApplicationContext().getFilesDir().getPath().toString() + "/your.properties"; 
     File file = new File(filePath); 
     FileInputStream f = new FileInputStream(file); 

     ObjectInputStream s = new ObjectInputStream(f); 

     HashMap<String, Object> hashFromFile=(HashMap<String, Object>) s.readObject(); 
     s.close(); 
     Log.e("hashfromfileLOCAL", ""+hashFromFile); 

     return hashFromFile; 
    } 
+0

這也是一個好方法,但作爲如果你想在散列內保存散列,你可以使用JSONArray :) –

1

Gson是一個Java庫,用於將Java對象轉換成JSON字符串和副詩句。 我在我的項目中遇到過同樣的問題,並使用Gson將HashMap轉換爲字符串,將其保存到SharedPreferences中,然後將其恢復到其他活動中。

要存儲的地圖:

SharedPreferences preferences = getSharedPreferences("com.your.package", MODE_PRIVATE); 
Type genericType = new TypeToken<HashMap<String, String>>() {}.getType(); 
String serializedHashMap = Helpers.serializeWithJSON(your_hashmap, genericType); 
preferences.edit().putString("Somename", serializedHashMap).commit(); 

serializeWithJSON():

public static String serializeWithJSON(Object o, Type genericType) { 
    Gson gson = new Gson(); 
    return gson.toJson(o, genericType); 
} 

反序列化:

Gson gson = new Gson(); 
Type genericType = new TypeToken<HashMap<String, String>>() {}.getType(); 
HashMap<String, String> hashMap = gson.fromJson(preferences.getString("Somename", "Errormessage"), genericType); 

持久地將其存儲在一個文件中,使用amalBit的答案。