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
Instead of casting it, you can do something like
Boolean.parseBoolean(string);
Here's some of the source code for the Boolean class in java.
// Boolean Constructor for String types.
public Boolean(String s) {
this(toBoolean(s));
}
// parser.
public static boolean parseBoolean(String s) {
return toBoolean(s);
}
// ...
// Here's the source for toBoolean.
// ...
private static boolean toBoolean(String name) {
return ((name != null) && name.equalsIgnoreCase("true"));
}
So as you can see, you need to pass a string with the value of "true" in order for the boolean value to be true. Otherwise it's false.
assert new Boolean( "ok" ) == false;
assert new Boolean( "True" ) == true;
assert new Boolean( "false" ) == false;
assert Boolean.parseBoolean( "ok" ) == false;
assert Boolean.parseBoolean( "True" ) == true;
assert Boolean.parseBoolean( "false" ) == false;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With