Android - 从SharedPreferences设置和获取StringSet?

Raz*_*riz 9 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));
    }
Run Code Online (Sandbox Code Playgroud)

但是,事实证明Set<String> fetch是null并且我有一个空指针异常,这可能是因为我没有正确地存储或获取我的StringSet.

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

A H*_*ard 11

首先创建一个编辑器对象:

SharedPreferences.Editor editor = prefs.edit();
Run Code Online (Sandbox Code Playgroud)

并使用编辑器对象来存储和获取您的字符串集,如下所示:

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

Set<String> fetch = editor.getStringSet("List", null);
Run Code Online (Sandbox Code Playgroud)