2012-05-30 162 views
9

我想知道是否可以在共享首选项中保存一个字符串数组,以这种方式,每次我们保存某个字符串时,都会将其存储在该数组中。在SharedPreferences中存储字符串数组

例如,我有一个具有特定ID的位置的列表,我想将其标记为收藏。 理想的情况是,在该数组中有一个数组并保存某个位置ID(我们称之为Location1),所以下次我想将新位置标记为收藏夹(我们称之为Location2)时,我将检索该数组到目前为止包含Location1)并添加我想要添加的这个新位置的ID(Location2)。

Android有方法来存储原始对象,但不是阵列。 任何想法,为了做到这一点,请?

+0

AFAIK共享prefrences用于原语数据类型 –

+0

http://stackoverflow.com/questions/7873682/is-it-possible-to-stored-classs-static-object-in-shared-preferenc e/7873759#7873759 –

回答

1

编写读取和写入串行化数组的方法。这不应该太难。只需将字符串数组平铺为您存储在首选项中的单个字符串即可。另一种选择是将数组转换为XML结构,然后将其存储在首选项中,但这可能是过度的。

23

这是可行的:I was just blogging about it

保存您的ARRAY

//String array[] 
//SharedPreferences prefs 
Editor edit = prefs.edit(); 
edit.putInt("array_size", array.length); 
for(int i=0;i<array.length; i++) 
    edit.putString("array_" + i, array[i]); 
edit.commit(); 

检索您的ARRAY

int size = prefs.getInt("array_size", 0); 
array = new String[size]; 
for(int i=0; i<size; i++) 
    prefs.getString("array_" + i, null); 

刚刚写道,所以可能会有错别字。

+3

查看本帖子的答案。 http://stackoverflow.com/questions/7057845/save-arraylist-to-sharedpreferences – AndroidLearner

+0

@Sherif elKhatib它的作品就像一个魅力!非常感谢 – noloman

+0

@noloman欢迎您检查博客的功能..更通用 –

15

你可以使阵列的JSON数组,然后将其存储这样的:

SharedPreferences settings = getSharedPreferences("SETTINGS KEY", 0); 
SharedPreferences.Editor editor = settings.edit(); 

JSONArray jArray = new JSONArray(); 
try { 
    jArray.put(id); 
} catch (JSONException e) { 
    e.printStackTrace(); 
} 

editor.putString("jArray", jArray.toString()); 
editor.commit(); 

然后,您可以获取数组是这样的:

SharedPreferences settings = getSharedPreferences("SETTINGS KEY", 0); 
try { 
    JSONArray jArray = new JSONArray(settings.getString("jArray", "")); 
} catch (JSONException e) { 
    e.printStackTrace(); 
} 

只是一个替代解决方案,我已经使用在过去