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

How to tell if my shared preferences already has a specific value

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

 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);