gpt4 book ai didi

android - 从 SharedPreferences 设置和获取 StringSet?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:21:20 25 4
gpt4 key购买 nike

我正在构建一个 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为 null,我有一个空指针异常,这可能是因为我没有正确存储或获取我的 StringSet。

最佳答案

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

SharedPreferences.Editor editor = prefs.edit();

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

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

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

关于android - 从 SharedPreferences 设置和获取 StringSet?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29195164/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com