Tobias D
Tobias D

Reputation: 97

How to save my location in a global variable

I am getting my GPS data via:

fusedLocationClient.lastLocation
            .addOnSuccessListener { location: Location? ->
                location2 = location
                var latitude =  location?.latitude
                var longitude = location?.longitude
                println(latitude)
                println(longitude)
                println("gps?")
                StopsFromWebservice().execute()
            }

which works. But I want to use the location in a different method. So I tried defining

var location2 : Location? = null

and call it via

fun FindClosestStops(location: Location?){
    for (i in 0..haltestellen_lat.size-1){
        var x=0.0
        var y=0.0
        var distance = 0.0
        x= (haltestellen_lat[i]-location?.latitude!!)*(haltestellen_lat[i]-location?.latitude!!)
        y= (haltestellen_lon[i]-location?.longitude!!)*(haltestellen_lon[i]-location?.longitude!!)
        distance = sqrt(x+y)
        StopDistances[i]= distance

        Haltestellen.add(distance.toString())

        println("distance = " + distance)
        println("FindClosestStops")
    }
    SortDistance()
    time.post(UpdateView);
}

but then android Studio kills my task with this error:

Caused by: kotlin.KotlinNullPointerException
    at com.xxx.yyy.zzz.FindClosestStops(fahrplanmap.kt:100)

which is exactly this code:

 x= (haltestellen_lat[i]-location?.latitude!!)*(haltestellen_lat[i]-location?.latitude!!)

how can I write my location data in x and y?

Upvotes: 0

Views: 530

Answers (1)

Kiskae
Kiskae

Reputation: 25603

You've defined location as nullable and use nullable accessors to access latitude and longitude. However immediately after that you use the non-nullable operator !! which produces the error.

Simply said, you either need to check if location is null and define behavior if that is the case, or figure out a way to ensure that method is never called while location is null.

Upvotes: 1

Related Questions