java - 如何判断我的共享偏好是否已经具有特定值

标签 java android key sharedpreferences

所以我有一些共同的偏好:

 public SharedPreferences prefs = this.getSharedPreferences("com.example.me1jmo.insult_generator", Context.MODE_PRIVATE);

我正在向其中添加新的键值对,如下所示:

int number = prefs.getAll().size();
        int newkey = ++number;
        String newkeystring = "" + newkey;
        prefs.edit().putString(newkeystring,saved).commit();

但是我不想添加已经添加的字符串。因此,我想检查我添加的字符串是否还不是我的共享首选项中的值。解决这个问题的最佳方法是什么?

(或者我可以切换我的值和键并检查我的共享首选项中是否还没有该键)

最佳答案

您可以使用 prefs.contains(newkeystring) 来检查该键的条目是否已存在。来自 documentation

Checks whether the preferences contains a preference.

编辑:

My key will not already exist, they will always be different I want to know if the value I'm entering is already in the preferences. –

那么唯一的解决方案是循环并检查该值是否存在。您可以使用 getAll 检索 SharedPreferences 内容(查看我的答案 here )

public boolean exits(String value) {
    Map<String, ?> allEntries = prefA.getAll();
    for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
        Log.d("map values", entry.getKey() + ": " + entry.getValue().toString());
        if ("yourvalue".equals(entry.getValue().toString()) {
            // the value exits; 
            return true;
        }
    } 
    return false;
}

并像 exits("theValueToCheck);

那样调用它

关于java - 如何判断我的共享偏好是否已经具有特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32987422/

相关文章:

java - 在mac上运行ant安装netbeans : Buildfile: build. xml不存在!构建失败

java - 解码时未找到类

javascript - Android 键盘在验证后无法在 webview 中工作

android - 检索系统默认的 Android 联系人图片

ios - 打印 NSDictionary 的键而不是值

android - 发布版本中的 Google Maps API key 不起作用

java - 为什么需要 `String[] args` 作为 main() 参数?

java - 在java中的同一行中打印

android - 在 Cocos2d-x 中加载 Base64 编码的图片

swift - Swift 4 中的 Smart KeyPaths 无法正常工作