How to get object type of preference in Android?
Asked Answered
K

3

5

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")) {}
Kilburn answered 2/11, 2015 at 13:20 Comment(4)
None that is part of the SDK. The assumption is that you know ahead of time what the data type is of your SharedPreferences values.Marguritemargy
@Marguritemargy it could be possible using getAll() which returns Map<String, ?>, and then using instanceof to test type. Even though it doesn't make any senseAnaclinal
@Blackbelt: I suppose. That feels like a "swatting a fly with a Buick" sort of solution, though. :-)Marguritemargy
it does feel that way @MarguritemargyAnaclinal
L
9

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

Leucoplast answered 2/11, 2015 at 13:28 Comment(1)
you might want to check kotlin version thisPocked
E
2

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();
}
Earn answered 28/11, 2017 at 17:5 Comment(0)
U
1

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 :)

Ulster answered 2/11, 2015 at 13:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.