public static boolean preferenceKeyExists(final SharedPreferences prefs, final String key) { final Map<String, ?> map = prefs.getAll(); return map.containsKey(key); // Doing prefs.getString(key) will crash if its boolean and exists }
Programming Tips - Android: Does a key exist in SharedPreferences
Date: 2020jun18
OS: Android
Language: Java
Q. Android: Does a key exist in SharedPreferences
A. You can NOT fetch it as a String a see if the String is empty if its
a boolean or other type - that causes an Exception!
So this is a safe way: