How to get a boolean value from an object

I tried to fix it in different ways, but I can not fix it. I am trying to get the boolean value of the Object passed inside this checkbox method:

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 added to java.lang.Boolean

+5
source share
4 answers

Instead of dropping it, you can do something like

 Boolean.parseBoolean(string);
+9
source

Here is some 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 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 "true" so that the boolean value is true. Otherwise, this is not true.

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;
+4
source

, , , , , newValue . , , , .

, . newValue . , :

boolean newValue;
if (newValue instanceof Boolean) { 
    changedValue = newValue; // autoboxing handles this for you
} else if (newValue instanceof String) {
    changedValue = Boolean.parseBoolean(newValue);
} else { 
    // handle other object types here, in a similar fashion to above
}

, . , , , , . , . , .

+2

If you know what yours Preferenceis CheckBoxPreference, you can call isChecked () . It returns boolean, not boolean, but probably close enough.

Below is the code from APIDemos Device Administration (DeviceAdminSample.java).

private CheckBoxPreference mDisableCameraCheckbox;

public void onResume() {
    ...
    mDPM.setCameraDisabled(mDeviceAdminSample, mDisableCameraCheckbox.isChecked());
    ...
}

public boolean onPreferenceChange(Preference preference, Object newValue) {
...
    boolean value = (Boolean) newValue;
...
    else if (preference == mDisableCameraCheckbox) {
        mDPM.setCameraDisabled(mDeviceAdminSample, value);
        reloadSummaries();
    }
    return true;
}
+1
source

All Articles