如何在android中的sharedpreferences中存储数组

时间:2014-11-18 09:22:56

标签: java android arrays sharedpreferences

我正在构建一个Android应用程序,用户从spinner工具中选择他的事件。

Spinner工具显示用户在第一次启动应用程序时选择的数组列表。

现在,我已经将应用程序启动页面中的数组列表解析为spinner活动类,并在spinner工具成功完成时使用它。

这是代码:

public static ArrayList<String> array;

这里,名称数组有arraylist。 我需要将它存储在sharedprefrences中。我怎么能这样做?

我是新手。

4 个答案:

答案 0 :(得分:1)

我建议不要使用putStringSet()因为它会搞砸你的数组顺序。

我建议在你的数组上运行for循环并为它们提供不同的键名。 +最后添加另一个String,它告诉你一旦你想读出SharedPreferences的字符串,数组有多长。

常规设置:

&#13;
&#13;
SharedPreferences sharedPreferences = getSharedPreferences("YOURKEYFILE", Activity.MODE_PRIVATE);
SharedPreferences.Editor sharedPreferencesEditor = sharedPreferences.edit();
&#13;
&#13;
&#13;

保存字符串数组:

&#13;
&#13;
for (int i = 0; i < array.size(); i++) {
    sharedPreferencesEditor.putString("StringArrayElement" +i, array.get(i));
}
sharedPreferencesEditor.putInt("StringArrayLength", array.size());
sharedPreferencesEditor.commit();
&#13;
&#13;
&#13;

读取字符串数组:

&#13;
&#13;
array.clear();
for (int i = 0; i < sharedPreferencesEditor.getInt("StringArrayLength", 0) {
    array.add(sharedPreferencesEditor.getString("StringArrayElement" +i, "");
}
&#13;
&#13;
&#13;

注意: 以上代码未经测试!如果你发现错误,社区会在那里纠正我。

答案 1 :(得分:0)

您可以将数组保存为Serializable对象。

//save the task list to preference
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
Editor editor = prefs.edit();
try {
    editor.putString(ARRAY, ObjectSerializer.serialize(array));
} catch (IOException e) {
    e.printStackTrace();
}
editor.commit();

并从SharedPreferences中检索它:

SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);

try {
    array = (ArrayList<String>) ObjectSerializer.deserialize(prefs.getString(ARRAY,
         ObjectSerializer.serialize(new ArrayList<String>())));
} catch (IOException e) {
    e.printStackTrace();
} catch (ClassNotFoundException e) {
    e.printStackTrace();
}

您可以从here

获取ObjectSerializer.java

答案 2 :(得分:0)

此代码可能对您有所帮助。您可以通过计数器i保存列表项目。

for(int i=0;i<list.size();i++)
    {
editor.putString(list.get(i)+i, list.get(i));
editor.commit();}
for(int i=0;i<list.size();i++)
    {
preferences.getString(list.get(i)+i, "");
    }

答案 3 :(得分:0)

最好使用 Set<String> ,因为API版本11引入了方法putStringSetgetStringSet,允许开发人员存储列表字符串值并分别检索字符串值列表。

保存列表

// Save the list.
editor.putStringSet("array", myStrings);
editor.commit();

获取列表

// Get the current list.
SharedPreferences settings = this.getSharedPreferences("YourActivityPreferences", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
Set<String> myStrings = settings.getStringSet("array", new HashSet<String>());