[英]FusedLocationProviderClient crash with java.lang.NullPointerException: parameter location specified as non-null is null
I'm using FusedLocationProviderClient in my app and it works fine to get user current location but suddenly I got this crash我在我的应用程序中使用 FusedLocationProviderClient 并且它可以很好地获取用户当前位置但突然我遇到了这个崩溃
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) // 崩溃发生在 (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
). Task.OnSuccessListener
是一个Java class没有参数可空性注释( @NotNull
或@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
).因此 Kotlin 无法确定类型是可为空还是不可为空,并且编译器不会抱怨location
的不安全使用(例如location.latitude
而不是location?.latitude
)。
There are 3 possible cases where the location can be null
, according to the docs :根据文档,在 3 种可能的情况下,位置可以是null
:
To sum up: Declare nullability explicitly and handle null-scenario .addOnSuccessListener { location: Location? -> /* null-safe code here */ }
总结一下:明确声明可空性并处理空场景.addOnSuccessListener { location: Location? -> /* null-safe code here */ }
.addOnSuccessListener { location: Location? -> /* null-safe code here */ }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.