Marlon
Marlon

Reputation: 1897

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")) {}

Upvotes: 5

Views: 3848

Answers (3)

Dan Chaltiel
Dan Chaltiel

Reputation: 8513

If you expect a String, you can also use a try/catch clause:

try {
    String strValue = sharedPreferences.getString("key_name","default value")
    actionIfString();
} catch (ClassCastException e) {
    actionIfNotString();
}

Upvotes: 2

Narayan Acharya
Narayan Acharya

Reputation: 1499

What is expected is you ought to know the data type of your SharedPreference values.

All the shared prefrences that you put are inserted into a Map. A map cannot have duplicate keys that hold different values. When you use the put operation it basically overwrites the value associated with the key if they key already exists in the map. You can find how a Map "put" method works here - Java Map

So checking the instanceof for two(or multiple) data types as suggested by @Maloubobola, is kind of absurd since the key can only one value and that value can be of only one data type(which you should know :P). You can do that but it doesn't make sense like @Blackbelt commented.

All the best :)

Upvotes: 1

ThomasThiebaud
ThomasThiebaud

Reputation: 11989

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

Upvotes: 9

Related Questions