我无法访问从fetchlocation((函数到另一个函数callAPI((函数的本地变量数据(纬度和经度(以获取位置。。这就是为什么我使用全局变量q来获取它,但仍然显示错误。这是代码:
class BlankFragment : Fragment() {
lateinit var fusedLocationProviderClient: FusedLocationProviderClient
private val key = "5a812faf9e1e4a66b17223056210911"
private val days = 1
private var q:String=""
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(activity)
fetchLocation()
callAPI()
}
private fun fetchLocation() {
val task =fusedLocationProviderClient.lastLocation
if (context?.let { ActivityCompat.checkSelfPermission(it,android.Manifest.permission.ACCESS_FINE_LOCATION) }
!= PackageManager.PERMISSION_GRANTED && context?.let {
ActivityCompat
.checkSelfPermission(it,android.Manifest.permission.ACCESS_COARSE_LOCATION)
} != PackageManager.PERMISSION_GRANTED
){
ActivityCompat.requestPermissions(context as Activity, arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION),101)
return
}
task.addOnSuccessListener {
if (it!= null){
q="$it.latitude,$it.longitude"
}
}
}
private fun callAPI(){
apiServices.getUserDetails(key, q, days).enqueue(
)
}
}
您的代码有一个大问题。您需要fetchLocation()
来更新q变量,然后调用callAPI()
,但在用户不提供其位置权限的情况下,您也不调用callAPI()
。
你可以试试这个解决方案:
private fun fetchLocation(result: (String) -> Unit) {
val task =fusedLocationProviderClient.lastLocation
if (context?.let { ActivityCompat.checkSelfPermission(it,android.Manifest.permission.ACCESS_FINE_LOCATION) }
!= PackageManager.PERMISSION_GRANTED && context?.let {
ActivityCompat
.checkSelfPermission(it,android.Manifest.permission.ACCESS_COARSE_LOCATION)
} != PackageManager.PERMISSION_GRANTED
){
ActivityCompat.requestPermissions(context as Activity, arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION),101)
return
}
task.addOnSuccessListener {
if (it!= null){
result("$it.latitude,$it.longitude")
}
}
}
private fun callAPI(q: String){
apiServices.getUserDetails(key, q, days).enqueue(
)
}
fetchLocation() { q ->
callAPI(q)
}