2014-03-02 106 views
1

我有一個HashMap是這樣的:如何將hashmap值保存到sharedpreference?

static final ArrayList<HashMap<String,String>> tasklist = new ArrayList<HashMap<String,String>>(); 

我想將hashMap ArrayList內容存儲sharedpreference

我該怎麼做?而且,如何在之後檢索值?

回答

2

這裏是我在我的項目中使用這種東西,它可以幫助你希望:)

下面是如何拯救,

Set<String> set = new HashSet<String>(); 
SharedPreferences prefs = getApplicationContext().getSharedPreferences(
    "My Preferences", Context.MODE_PRIVATE); 
SharedPreferences.Editor prefsEditor = prefs.edit(); 
prefsEditor.putStringSet("myStringSet", set); 
prefsEditor.commit(); 

而且這裏是如何獲取它們:

Set<String> set = new HashSet<String>(); 
SharedPreferences prefs = getApplicationContext().getSharedPreferences(
    "My Preferences", Context.MODE_PRIVATE); 
set = prefs.getStringSet("myStringSet", null); 
Set<String> set = new HashSet<String>(); 
SharedPreferences prefs = getApplicationContext().getSharedPreferences(
    "My Preferences", Context.MODE_PRIVATE); 
set = prefs.getStringSet("myStringSet", null); 
+0

如果例如內容是這樣的,你如何提取內容? [「{action = some text,task = some text}」,「{action = some text 2,task = some text 2}」] – user3325919

+0

@ user3325919所以讓我弄清楚這一點。你使用的數據類型就像鍵值?你有鑰匙的地方,與它相對應的價值?因爲你已經寫了行動=一些文字和任務= sometext。我假設「sometext」是字符串類型。什麼類型是「行動」和「任務」? – Ogen

+0

@Ogen:你的方式只適用於'String'不適用於'Object'的權利? –

0

我通過使用GSON框架將它們序列化爲JSON,將Java對象存儲在Shared Preferences中。我更喜歡JSON,因爲它是人類可讀的,並且在對後端服務進行HTTP調用時,我的應用程序已經處理了JSON。我認爲我不需要創建/維護SQL Lite數據庫就具有適當的複雜性。

我有一個更有趣的用途是維護一個應用程序範圍的上傳隊列。我的應用程序允許將視頻和圖像上傳到後端服務器。我在共享偏好內的狀態列表中追蹤它們。任何需要這些數據的活動都可以從這些「隊列」中讀取,而不是將數據全部傳遞給這些「隊列」。

相關問題