android - 为什么在这种情况下位置总是空的?
问题描述
谁能告诉我为什么当我initPetrolStationList()
在第一个if
条件下调用函数currentLocation
时总是为空但是当我调用 te 函数时addPetrolStation(v: View)
被初始化?我希望initPetrolStationList()
调用函数时currentLocation
不为空。
class PetrolStationListActivity : AppCompatActivity() {
private lateinit var fusedLocationProviderClient: FusedLocationProviderClient
private lateinit var listView: RecyclerView
private var currentLocation: Location? = null
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
//some code
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.petrol_station_list_view)
requestLocationPermission()
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
getLastLocation()
initPetrolStationList()
}
fun addPetrolStation(v: View) {
if (currentLocation != null) {
val googleMapController = GoogleMapsController()
googleMapController.getPetrolStationFromGoogle(object : GoogleResponse {
override fun getLocation(): Location = currentLocation!!
override fun getResponse(body: GoogleMapResponse) {
if (body.status == "OK") {
val intent = Intent(applicationContext, PetrolStationActivity::class.java)
v.context.startActivity(intent)
} else {
Toast.makeText(applicationContext, "Petrol station not found", Toast.LENGTH_LONG).show()
}
}
})
}
}
@SuppressLint("MissingPermission")
private fun getLastLocation() {
fusedLocationProviderClient.lastLocation.addOnCompleteListener {
if (it.isSuccessful) {
currentLocation = it.result!!
Log.d("Current location: ", "Lat:${currentLocation!!.latitude}, Lng:${currentLocation!!.longitude}")
} else {
Log.d("Location exception: ", it.exception?.message)
Toast.makeText(this, "Location not found :( ", Toast.LENGTH_LONG).show()
}
}
}
private fun initPetrolStationList() {
if (currentLocation != null) {
val petrolStationController = PetrolStationController()
//some code
} else Toast.makeText(this, "Location not found", Toast.LENGTH_LONG).show()
}
}
解决方案
如果你之后initPetrolStationList
从内部调用,则不会为空。getLastLocation
currentLocation = it.result!!
currentLocation
推荐阅读
- angular - Angular - mat-tab 中的动态组件
- c# - 多个计时器在 .NET 中的行为不规律
- javascript - Javascript MutationObserver:如何突出显示已编辑的 DOM 元素?
- javascript - 跟踪点击广告不断刷新我的网页
- java - Java多线程等待任务结束
- selenium - 在 Selenium 中按顺序运行测试 - 如何设置测试设置和拆卸
- c++ - 我怎样才能让 gcc 警告我“int i = i;”
- docker - 通过 Vagrantfile 安装 Docker
- r - 使用 stringr 将字符对象转换为数字对象
- php - 如何从多个图像源中获取单个图像源