从 SharedPreferences 设置和获取 StringSet?

Setting and fetching a StringSet from SharedPreferences?

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

我不想使用数据库,所以我知道我应该使用 SharedPreferences 来存储登录人员列表。我希望能够重置此列表,以便将个人登录数据保存为字符串而 NOT 因为 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。

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

SharedPreferences.Editor editor = prefs.edit();

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

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

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

您可以将结果写入 JSON 字符串并将它们存储在共享首选项中,如下所示:

但是,如果您选择沿着您当前所在的路线前进,那么您将不得不存储一个包裹。

如另一个答案所述;如果您正在为 API 11+.

构建,则可以使用 putStringSet()、getStringSet()