Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android check SharedPreferences for value type

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

like image 863
cyborg86pl Avatar asked Apr 13 '15 22:04

cyborg86pl


2 Answers

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");

}
like image 135
Christian Abella Avatar answered Sep 18 '22 16:09

Christian Abella


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)
like image 30
valvoline Avatar answered Sep 18 '22 16:09

valvoline