在SharedPreferences中存储String数组

时间:2012-05-30 09:48:53

标签: android storage sharedpreferences

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

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

Android有存储基本对象的方法,但不存在数组。 为了做到这一点有什么想法吗?

3 个答案:

答案 0 :(得分:23)

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

保存您的阵列

//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();

检索您的阵列

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

刚写过,所以可能会有拼写错误。

答案 1 :(得分: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();
}

只是我过去使用的替代解决方案

答案 2 :(得分:1)

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

相关问题