Search code examples
javaandroidkotlinandroid-gpsfusedlocationproviderclient

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

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))
            }

Solution

  • 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:

    • Location is turned off in the device settings. The result could be null even if the last location was previously retrieved because disabling location also clears the cache.
    • The device never recorded its location, which could be the case of a new device or a device that has been restored to factory settings.
    • Google Play services on the device has restarted, and there is no active Fused Location Provider client that has requested location after the services restarted.

    To sum up: Declare nullability explicitly and handle null-scenario .addOnSuccessListener { location: Location? -> /* null-safe code here */ }