SharedPreferences has a
contains(String key)
method. Used it to check if entry with your given key exists.
SharedPreferences prefs = context.getSharedPreferences("SharedPref_Name", Context.MODE_PRIVATE);
if(pref.contains("Key"){
String deviceToken = prefs.getString("Key", null);
}else{
// New User
}
or Use the
getAll()
method of android.content.SharedPreferences.
Map<String, ?> map = context.getSharedPreferences("SharedPref_Name", Context.MODE_PRIVATE).getAll();
for (Map.Entry<String, ?> entry: prefsMap.entrySet()) {
// entry.getValue().toString() will give the key. check it against the key that you want.
}
in Kotlin
val prefs = context?.getSharedPreferences("SharedPref_Name", Context.MODE_PRIVATE)
if(prefs?.contains("Key")!!){
val deviceToken = prefs.getString("Key", null);
}
or
(context?.getSharedPreferences("",Context.MODE_PRIVATE))?.all?.forEach {
//access key using it.key & value using it.value
Log.d("Preferences values",it.key() + ": " + it.value()
}