我通过以下方式获取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中写入位置数据?
答案 0 :(得分:1)
您已将location
定义为可为空,并使用可为空的访问器来访问latitude
和longitude
。但是,此后立即使用non-nullable
运算符!!
会产生错误。
简单地说,您要么需要检查location
是否为null并定义行为(如果是这种情况),要么想出一种方法来确保在location
为null时永远不要调用该方法。 / p>