I'm using FusedLocationProviderClient in my app and it works fine to get user current location but suddenly I got this crash
java.lang.NullPointerException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkNotNullParameter, parameter location
here is how I define it inside my activity
private lateinit var fusedLocationClient: FusedLocationProviderClient
//
fusedLocationClient =
LocationServices.getFusedLocationProviderClient(this)
// the crash happens on the next code on (addOnSuccessListener)
fusedLocationClient.lastLocation
.addOnSuccessListener { location ->
lat = location.latitude
lng = location.longitude
goToLocationOnMap(LatLng(lat, lng))
}
The Task.OnSuccessListener
is a Java class without paramenter-nullability annotation (@NotNull
or @Null
). Therefore Kotlin cannot figure out if the type is nullable or not-nullable and the compiler does not complain about unsafe usage of location
(eg. location.latitude
instead of location?.latitude
).
There are 3 possible cases where the location can be null
, according to the docs:
To sum up: Declare nullability explicitly and handle null-scenario .addOnSuccessListener { location: Location? -> /* null-safe code here */ }