Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Kotlin 如何在全局变量中保存我的位置_Kotlin_Android Gps - Fatal编程技术网

Kotlin 如何在全局变量中保存我的位置

Kotlin 如何在全局变量中保存我的位置,kotlin,android-gps,Kotlin,Android Gps,我通过以下方式获取GPS数据: fusedLocationClient.lastLocation .addOnSuccessListener { location: Location? -> location2 = location var latitude = location?.latitude var longitude = location?.longitude

我通过以下方式获取GPS数据:

fusedLocationClient.lastLocation
            .addOnSuccessListener { location: Location? ->
                location2 = location
                var latitude =  location?.latitude
                var longitude = location?.longitude
                println(latitude)
                println(longitude)
                println("gps?")
                StopsFromWebservice().execute()
            }
这很有效。 但是我想用另一种方法来使用这个位置。所以我试着定义

var location2 : Location? = null
并通过

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);
}
但是安卓工作室用以下错误终止了我的任务:

Caused by: kotlin.KotlinNullPointerException
    at com.xxx.yyy.zzz.FindClosestStops(fahrplanmap.kt:100)
这就是代码:

 x= (haltestellen_lat[i]-location?.latitude!!)*(haltestellen_lat[i]-location?.latitude!!)
如何在x和y中写入位置数据?

您已将位置定义为可空,并使用可空访问器访问纬度和经度。但是,之后立即使用不可为空的运算符!!这会产生错误


简单地说,您要么需要检查location是否为null并定义行为(如果是这种情况),要么想办法确保location为null时永远不会调用该方法。

谢谢您的快速回答。可悲的是,我对kotlin还很陌生,你知道我如何在另一个函数中访问我的位置并将其存储在变量中吗?你最大的错误是依赖lastLocation,当你第一次启动应用程序时,它几乎总是空的。您必须预料到这一点,并启动一个适当的位置侦听器,然后在其中启动需要onLocationChanged中的位置的操作,请参见。另外,尝试将位置和内容作为参数传递,例如StopsFromWebservice.executelocation请参阅用法假设这是一个异步任务