How to get Boolean value from Object

David Prun picture David Prun · May 17, 2012 · Viewed 30.6k times · Source

I tried different ways to fix this, but I am not able to fix it. I am trying to get the Boolean value of an Object passed inside this method of a checkBox:

public boolean onPreferenceChange(Preference preference, Object newValue) 
{
    final String key = preference.getKey();
    referenceKey=key;
    Boolean changedValue=!(((Boolean)newValue).booleanValue()); //ClassCastException occurs here
}

I get:

java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Boolean

Answer

OmniOwl picture OmniOwl · May 17, 2012

Instead of casting it, you can do something like

 Boolean.parseBoolean(string);