Android-从SharedPreferences设置和获取StringSet? [英] Android - Setting and Fetching a StringSet from SharedPreferences?

查看:119
本文介绍了Android-从SharedPreferences设置和获取StringSet?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Good day, I am building an Android Application. I want to store a set of strings in the Preferences to order to track who used the application based on their log in information.

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

I don't want to use a database so I know that I should use SharedPreferences to store a list of people who logged in. I want to be able to reset this list so keeping the individual log in data as Strings and NOT as StringSets is not an option. Using individual Strings means that I'll have to keep another list of those strings just so I can clean them up when I want to. A StringSet is easier to maintain.

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

Here's what I did thus far:

    //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>提取为空,并且我有一个空指针异常,这可能是因为我没有正确存储或提取我的StringSet.

However, it turns out that the Set<String> fetch was null and I'm having a null pointer exception and it's probably because I wasn't storing or fetching my StringSet properly.

有人可以帮助我解决我的问题吗?我傻眼了,觉得自己正在忽略一些简单的事情.很感谢任何形式的帮助.谢谢你.

Can anyone help me with my problem? I'm dumbfounded and I feel like I'm overlooking something simple. Any help is very much appreciated. Thank you.

推荐答案

首先创建编辑器对象:

SharedPreferences.Editor editor = prefs.edit();

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

And use the editor object to store and fetch your string set like this :

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

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

这篇关于Android-从SharedPreferences设置和获取StringSet?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆