0

So I have some shared preferences:

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

And I am adding new key value pairs to it like so:

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

However I don't want to add a string that has already been added. So I want to check that the string I am adding is not already a value in my shared preferences. What would be the best way to go about this?

(or could I just switch my values and keys around and check that I don't already have that key in my shared preferences)

James
  • 129
  • 4
  • 18
  • 1
    Possible duplicate of [android: check if value is present in Shared Preferences](http://stackoverflow.com/questions/8757573/android-check-if-value-is-present-in-shared-preferences) – Rahul Tiwari Oct 07 '15 at 08:35
  • check this http://stackoverflow.com/a/17885456/1529129 – Rahul Tiwari Oct 07 '15 at 08:35

1 Answers1

1

you can use prefs.contains(newkeystring) to check if an entry for that key exits already. From the documentation

Checks whether the preferences contains a preference.

Edit:

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. –

Then the only solution is to loop and check if the value exits. The retrieve the SharedPreferences content you can use getAll (check my answer 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;
}

and call it like exits("theValueToCheck);

Community
  • 1
  • 1
Blackbelt
  • 156,034
  • 29
  • 297
  • 305
  • 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. – James Oct 07 '15 at 08:40