so i have this method:
class A(){
private Boolean Flag;
public java.lang.Boolean getFlag()
{
return this.Flag;
}
public java.lang.Boolean setFlag(Boolean Flag)
{
this.Flag = Flag ;
}
}
classB(){
boolean navalFlag = fancyObj.getFlag()
form.setNavalFlag(navalFlag?"Y":"N";
}
database returns null and Flag is set to null.
What is a foolproof way where I can 100% avoid NPEs? I know Boolean to boolean casting is not a guarantee as seen from here
Update:
stepping through the code, the NPE is thrown in fancyObj.getFlag()...which doesn't make sense to me. i would expect the NPE thrown in .setNavalFlag....
What is a foolproof way where I can 100% avoid NPEs?
One foolproof way is to explicitly check for null and to not attempt to unbox the Boolean unless you know it's not null.
To take your current code as an example:
boolean navalFlag = fancyObj.getFlag()
This tries to unbox the Boolean. If it's null, you get an NPE.
The following modification will not have this problem:
Boolean navalFlag = fancyObj.getFlag()
form.setNavalFlag((navalFlag != null && navalFlag) ? "Y" : "N");
Boolean navalFlag = fancyObj.getFlag()
form.setNavalFlag((navalflag != null && navalFlag) ? "Y" : "N");
Edit of the Edit, as I had understood wrongly your comment :
See my answer to the comment: boolean navalFlag = fancyObj.getFlag() is automatically translated to boolean navalFlag = fancyObj.getFlag().booleanValue()
Change your method
public java.lang.Boolean getFlag()
{
return this.Flag;
}
to something like
public java.lang.Boolean getFlag()
{
(Flag==null) ? Boolean.FALSE : Flag;
}
Use boolean primitive type, not wrapper in your value object.
If you retrieve the value from database yourself, you will have to be careful, you will have to understand how to interpret null, normally it is false.
Related
I have a utility function which convert parseDouble value to string.
public static BigDecimal setValue(Object o) {
BigDecimal value = new BigDecimal(0);
if(o!= Null){
value=BigDecimal.valueOf(Double.parseDouble(o.toString()));
}
return value;
}
I have tried with (o!=null && !isEmpty(o)) and (o!="" && o!=null) but it is still throwing same error.
Transaction amount which is processing this utility function contains empty value.
Firstly I don't understand why you are taking object type as an input, however to resolve your issue you can do something like this. But I would strongly advice you to change the method signature it is misleading.
public static BigDecimal setValue(Object o) {
var value = new BigDecimal(0);
if (o != null) {
if(o instanceof String) {
if (((String) o).trim().length()>0) {
value = new BigDecimal((String) o);
}
}
}
return value;
}
I would change the method signature to BigDecimal setValue(String s). Your null check and length check code should then work fine.
Also the method name is misleading. The method does not set anything. Something like convertToBigDecimal would be clearer.
I have a code like this and when I am running it under sonar, it always complain on this line value.contains("true")
String value = getValue("/data/" + set, property);
if (!Strings.isNullOrEmpty(value)) {
if (value.contains("true")) {
return true;
} else {
return false;
}
} else {
return false;
}
Here is the message it is giving me: NullPointerException might be thrown as 'value' is nullable here
I am already checking value for null check just above then why it is complaining inside? Am I doing something wrong?
Update:
After Andy's suggestion. I rewrote something like this:
String value = getValue("/data/" + set, property);
if (value!=null) {
return Boolean.parseBoolean(value);
}
return false;
It's likely that sonar doesn't understand the semantics of Strings.isNullOrEmpty.
You can make it less confusing all round if you were to write the condition as:
if (value != null) {
It doesn't really matter if you call contains on an empty string.
Also, this:
if (value.contains("true")) {
return true;
} else {
return false;
}
is more easily written as
return value.contains("true");
Overall, you can write this as:
return value != null && value.contains("true");
Edit for your update: if you're using Boolean.parseBoolean, you don't even need the null check. parseBoolean returns false for a null input.
String value = getValue("/data/" + set, property);
return Boolean.parseBoolean(value);
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;
From the code you posted, and the result you are seeing, it doesn't look like newValue is a boolean. So you try to cast to a Boolean, but it's not one, so the error occurs.
It's not clear what you're trying to do. Ideally you'd make newValue a boolean. If you can't do that, this should work:
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
}
Note that this solution isn't really ideal, and is somewhat fragile. In some instances that is OK, but it is probably better to re-evaluate the inputs to your method to make them a little cleaner. If you can't, then the code above will work. It's really something only you can decide in the context of your solution.
If you know that your Preference is a CheckBoxPreference, then you can call isChecked(). It returns a boolean, not a Boolean, but that's probably close enough.
Here is some code from the APIDemos Device Administration sample (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;
}
I'm having a really frustrating problem with SharedPreference.getBoolean in android. See the following snippet:
Map<String, ?> all = preferences.getAll();
Object x = all.get("EnableMedia");
boolean v = preferences.getBoolean("EnableMedia", (Boolean) null);
I can see in the debugger that 'x' is a Boolean and it is true.
Yet, if I execute the next line, preferences.getBoolean, it throws an exception. What gives?!
Look at this call:
preferences.getBoolean("EnableMedia", (Boolean) null);
Now look at the signature of getBoolean:
public abstract boolean getBoolean (String key, boolean defValue)
Note that it's a boolean value, not a Boolean value. So what's actually happening is your code is something like this:
Boolean tmp = null;
preferences.getBoolean("EnableMedia", tmp.booleanValue());
That will throw a NullPointerException, as you're calling a method on a null reference.
You need to pass in a valid boolean value, e.g.
preferences.getBoolean("EnableMedia", true);
I can't find any method on the Boolean class to serialize a Boolean to "1" and "0" instead of "true" and "false".
Is there any native function to do that ? If not, what is the best way (most optimized way) ?
Update: I indeed mean to produce a String out of a Boolean.
If you're talking about producing a String from a given Boolean, then no, there is no built-in method that produces "0" or "1", but you can easily write it:
public static String toNumeralString(final Boolean input) {
if (input == null) {
return "null";
} else {
return input.booleanValue() ? "1" : "0";
}
}
Depending on your use case, it might be more appropriate to let it throw a NullPointerException if input is null. If that's the case for you, then you can reduce the method to the second return line alone.
You can use CompareTo:
public static Integer booleanToInteger(Boolean bool)
{
if(bool == null) return null;
else return bool.compareTo(Boolean.FALSE);
}
If you want to serialise to a char you can do
public static char toChar(final Boolean b) {
return b == null ? '?' : b ? '1' : '0';
}
I am not sure but just throwing it out. you can use your own Decorator class.
Use Thrift API:
TSerializer serializer = new TSerializer(new TSimpleJSONProtocol.Factory());
String json = serializer.toString(object);
It will boolean to 0 or 1 instead of true/false.