【发布时间】:2019-03-26 18:19:10
【问题描述】:
我通过以下方式获取 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);
}
但随后 android Studio 用这个错误杀死了我的任务:
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 中写入我的位置数据?
【问题讨论】:
-
您最大的错误是依赖
lastLocation,当您第一次启动应用程序时,它几乎总是为空。您必须预料到这一点并启动一个适当的位置侦听器,并在那里开始您需要来自onLocationChanged的位置的操作(请参阅developer.android.com/guide/topics/location/strategies)。还尝试将位置和事物作为参数传递,例如StopsFromWebservice().execute(location)(请参阅用法developer.android.com/reference/android/os/AsyncTask,假设这是一个异步任务)
标签: kotlin android-gps