Hey Guys, I received NullPointerException in logs ...
# android
d
Hey Guys, I received NullPointerException in logs even after putting a check for 'null'. Can anyone tell me how and when can I get NullPointerException for checking "isPreview" in the below statement...
Copy code
if (lastWallpaperEngine != null && !lastWallpaperEngine!!.isPreview) {
}
Logs received in play-store...
java.lang.NullPointerException
  at android.service.wallpaper.WallpaperService$Engine.isPreview (WallpaperService.java:390)
  at VideoWallpaperEngine.onSurfaceDestroyed (VideoWallpaperService.java:158)
v
Hello! The issue there is that you are evaluating a null value (isPreview is null).
If (null) is going to fail
j
@Deepti M always think about the worst case what can happen 🙂 there are 2 things that could go wrong:
lastWallpaperEnging
is not null, but nullified just before you call
!lastWallpaperEnging...
This could for example happen with async code, or perhaps by getting the value it will nullify it (I know that it is weird but in theory you can do that with kotlin) Then you have indeed the case that
lastWallpaperEnging
is not null, but the
isPreview
variable. the best way to check this, is to use Kotlin as kotlin and not as Java. Meaning: you never write the old Java null check
if (stuff != null)
but you write it as kotlin:
Copy code
if (lastWallpaperEngine?.isPreview == false) {}
This will only return true if your value is not null and also false. It has a double null check inside, because if either
lastWallpaperEngine
or
isPreview
is null you are safe.
👍 2
d
oh wow, I was so wrong. I mean, I didn't realise that I am writing Java code to be safe. This is just because I am new to Kotlin. Thanks @Joost Klitsie for explaining the issue so well! Will never forget this in future. Also Thanks to @Valentin Moscone for confirming the case!
💯 2