Search code examples
androidsharedpreferencespreferencesobject-type

How to get object type of preference in Android?


I can get a String from the shared preferences by using:

sharedPreferences.getString("key_name","default value");

But how can I check if key_name is actually a String?

What if it is a Boolean key value?

Is there a method we can use like:

if(sharedPreferences.isTypeOf(Boolean,"key_name")) {}

Solution

  • If you know you will get a boolean you can use

    sharedPreferences.getBoolean("key_name",true);
    

    Otherwise you can do (not tested, based on doc)

    Map<String, ?> all = sharedPreferences.getAll();
    if(all.get("key_name") instanceof String) {
        //Do something
    }
    else if(all.get("key_name") instanceof Boolean) {
        //Do something else
    }
    

    But you are suppose to know what you stored in your SharedPrefrences