首页 > 解决方案 > 为什么在这种情况下位置总是空的?

问题描述

谁能告诉我为什么当我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()
    }

}

标签: androidkotlinlocation

解决方案


如果你之后initPetrolStationList从内部调用,则不会为空。getLastLocationcurrentLocation = it.result!!currentLocation


推荐阅读