I am creating an application which retrieves images from the web. In case the image cannot be retrieved another local image should be used.
While trying to execute the following lines:
Drawable drawable = Common.getDrawableFromUrl(this, product.getMapPath()); if (drawable.equals(null)) { drawable = getRandomDrawable(); }
The line if(drawable.equals(null)) throws an exception if drawable is null.
Does anyone know how should the value of drawable be checked in order not to throw an exception in case it is null and retrieve the local image (execute drawable = getRandomDrawable())?
), also known as the strict equality operator, to be sure that the value in question is definitely not null: object !== null . That code checks that the variable object does not have the value null . Some developers prefer the double equality operator ( == or !=
According to the Java spec, null is a type that can be assigned to an object variable (as a value as noted in the comment). You cannot instantiate or create variables of this type though, you must use the literal null provided by the compiler.
Check if it is null: if (date == null) {...} Check if it is not null: if (date !=
out. println("(Object)string == number: " + ((Object)string == number)); To conclude this post and answer the titular question Does null equal null in Java? the answer is a simple yes.
Drawable drawable = Common.getDrawableFromUrl(this, product.getMapPath()); if (drawable == null) { drawable = getRandomDrawable(); }
The equals()
method checks for value equality, which means that it compares the contents of two objects. Since null
is not an object, this crashes when trying to compare the contents of your object to the contents of null
.
The ==
operator checks for reference equality, which means that it looks whether the two objects are actually the very same object. This does not require the objects to actually exist; two nonexistent objects (null
references) are also equal.
Edited Java 8 Solution:
final Drawable drawable = Optional.ofNullable(Common.getDrawableFromUrl(this, product.getMapPath())) .orElseGet(() -> getRandomDrawable());
You can declare drawable
final
in this case.
As Chasmo pointed out, Android doesn't support Java 8 at the moment. So this solution is only possible in other contexts.
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