如何获取存储在sharedpreference中的字符串数组值?

时间:2014-03-02 02:05:41

标签: android sharedpreferences

所以我将string array存储到shared preference。它保存如下:

["{action= some text, task= some text}", "{action= some text 2, task= some text 2 }" ]

如何检索操作和任务键中指示的字符串?

1 个答案:

答案 0 :(得分:0)

根据您对问题的评论(您现在已删除),您的字符串不是生成有效JSON的最佳方式...

["{action= some text, task= some text}", "{action= some text 2, task= some text 2 }" ]

在上面使用JSON,actiontask看起来应该是键,应该用引号括起来,即"action""task"

在这种情况下,代替使用=,键/值对应由:分隔,并假设some textsome text 2(值)也是字符串需要被引号括起来。

最后一个JSON对象没有被引号括起来,所以你的JSON字符串应该看起来像这样......

[{"action":"some text", "task":"some text"}, {"action":"some text 2", "task":"some text 2"}]

现在,假设您有一个代表上述内容的JSONArray,您可以使用类似的内容将其保存到SharedPreferences ...

prefs.edit().putString("json_string", myJsonArray.toString()).commit();

...然后检索它使用...

JSONArray myJsonArray = new JSONArray(prefs.getString("json_string", ""));

当您检索到JSONArray时,您可以使用...

获取每个JSONObject
myJsoObject = myJsonArray.getJSONObject(0); // In this case it's index 0 - use a for loop to retrieve all

然后您可以按照以下方式获取actiontask ...

String actionValue = myJsonObject.getString("action");
String taskValue = myJsonObject.getString("task");
相关问题