Reputation: 1
I want to know if some key-value pair already exists in shared preferences or not.
sharedPref=getApplicationContext().getSharedPreferences("sharedf",Context.MODE_PRIVATE);
editor=sharedPref.edit();
editor.putString("secretKey",e1.getText().toString());
editor.commit();
Now I want to check if secretKey already exists or not in the sharedprefrences.
Upvotes: 0
Views: 90
Reputation: 389
android: check if value exists in Shared Preferences
:-Check this
Try contains(String key) Accorting to the Javadocs,
Checks whether the preferences contains a preference. Returns true if the preference exists in the preferences, otherwise false.
Upvotes: 0
Reputation: 12627
if (mPrefs.contains(SETTING_THEME)) {
// read the value
mThemeSettings = mPrefs.getString(SETTING_THEME, THEME_KEY_DEFAULT);
}
// create a new "prefs entry" (first start, after installing the app)
else mEditor.putString(SETTING_THEME, mThemeSettings).apply();
Upvotes: 0
Reputation: 1754
It is simple. There is a method:
public abstract boolean contains (String key)
You can read it here:
http://developer.android.com/reference/android/content/SharedPreferences.html
Upvotes: 3
Reputation: 5020
You can do that in next way
sharedPref=getApplicationContext().getSharedPreferences("sharedf",Context.MODE_PRIVATE);
String secretKey = sharedPref.getString("secretKey", null);
if (null == secretKey) {
// not exists
} else {
// exists
}
Upvotes: 0