2013-02-09 89 views
1

在不使用數據庫的情況下存儲對象的最快方式是什麼?如何在SharedPreferences中存儲ArrayList

例如,我想存儲一個列表,我可以回去添加或刪除酒店,但我不想創建一個數據庫,所有這些麻煩似乎是過分的。

如何在共享首選項中存儲數組列表或類似的簡單東西?

public class Hotel{ 
    String id, name, address, phoneNumber; 
    public String getName(){ 
    return name; 
    } 
etc 
} 
+1

嗯,我知道你不想聽到這個,但一個數據庫是你所需要的:D這是非常強大的,並沒有那麼難。 – AMerle 2013-02-09 15:34:24

+1

如果你的應用程序是API 11+,那麼你可以按照@ KLAL的建議。否則:我會說你把你的數組轉換成json並將它作爲字符串保存到sharedpreferences中,然後你將它讀作json並再次解析爲數組。 – yahya 2013-02-09 15:39:40

回答

5

我的建議是:

  1. 使用Gson任何類型的對象轉換成字符串
  2. 保存在SharedPreferences該字符串
  3. 相反的過程using Gson檢索您的對象
1
//Retrieve the values 
Set<String> set = new HashSet<String>(); 
set = myScores.getStringSet("key", null); 

//Set the values 
Set<String> set = new HashSet<String>(); 
set.addAll(listOfExistingScores); 
scoreEditor.putStringSet("key", set); 
scoreEditor.commit(); 
相關問題