I've got some key-value pairs in SharedPreferences
, there are ints, floats, Strings, etc. Is there any way to check if a given key is of a specific type?
EDIT
I've studied the documentation and available methods. Sadly, it seems to me that i'd need to make it a "dirty" way, just trying every get method until i get value different than default set as parameter. this is the only one i figured out, but don't like it much...
You can iterate through all the entries in SharedPreferences and check the data type of each entry by using getClass function of the value.
Map<String,?> keys = sharedPreferences.getAll();
for(Map.Entry<String,?> entry : keys.entrySet())
{
Log.d("map values", entry.getKey() + ": " + entry.getValue().toString());
Log.d("data type", entry.getValue().getClass().toString());
if ( entry.getValue().getClass().equals(String.class))
Log.d("data type", "String");
else if ( entry.getValue().getClass().equals(Integer.class))
Log.d("data type", "Integer");
else if ( entry.getValue().getClass().equals(Boolean.class))
Log.d("data type", "boolean");
}
maybe late for the party, but a kotlin approach could be:
fun readPreference(key: String) : Any? {
val keys = sharedPrefs?.all
if (keys != null) {
for (entry in keys) {
if (entry.key == key) {
return entry.value
}
}
}
return null
}
where sharedPrefs is something previous initialized as:
sharedPrefs = this.applicationContext.getSharedPreferences("userdetails", Context.MODE_PRIVATE)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With