Android - 从SharedPreferences设置和获取StringSet?

时间:2015-03-22 13:49:33

标签: android sharedpreferences

美好的一天,我正在构建一个Android应用程序。我想在首选项中存储一组字符串,以便根据其登录信息跟踪谁使用了该应用程序。

我不想使用数据库,因此我知道我应该使用SharedPreferences来存储登录的人员列表。我希望能够重置此列表,以便将各个数据作为字符串保存在数据中而不是StringSets不是一个选项。使用单独的字符串意味着我必须保留这些字符串的另一个列表,以便我可以在需要时清理它们。 StringSet更易于维护。

这是我到目前为止所做的事情:

    //this is my preferences variable
    SharedPreferences prefs = getSharedPreferences("packageName", MODE_PRIVATE);

    //I create a StringSet then add elements to it
    Set<String> set = new HashSet<String>();

    set.add("test 1");
    set.add("test 2");
    set.add("test 3");

    //I edit the prefs and add my string set and label it as "List"
    prefs.edit().putStringSet("List", set);

    //I commit the edit I made
    prefs.edit().commit();

    //I create another Set, then I fetch List from my prefs file
    Set<String> fetch = prefs.getStringSet("List", null);

    //I then convert it to an Array List and try to see if I got the values 
    List<String> list = new ArrayList<String>(fetch);

    for(int i = 0 ; i < list.size() ; i++){
        Log.d("fetching values", "fetch value " + list.get(i));
    }

然而,事实证明Set<String> fetch为空并且我有一个空指针异常,这可能是因为我没有正确存储或提取我的StringSet。 / p>

任何人都可以帮我解决我的问题吗?我傻眼了,我觉得我忽略了一些简单的事情。很感谢任何形式的帮助。谢谢。

2 个答案:

答案 0 :(得分:9)

首先创建编辑器对象:

SharedPreferences.Editor editor = prefs.edit();

使用编辑器对象来存储和获取您的字符串集:

editor.putStringSet("List", set);
editor.apply();

Set<String> fetch = editor.getStringSet("List", null);

答案 1 :(得分:1)

您可以将结果写入JSON字符串并将其存储在共享首选项中,如下所示:https://stackoverflow.com/a/5968562/617044

但是如果你选择沿着你目前所在的路线走下去,那么你将不得不存放一个可以存放的行为。

如另一个答案所述;如果你正在为API 11 +构建,你可以使用putStringSet(),getStringSet()。