Android 从函数访问变量并在内部类中使用

Android 从函数访问变量并在内部类中使用,android,kotlin,location,global-variables,Android,Kotlin,Location,Global Variables,我有这个getLastLocation函数,它获取当前用户位置并将它们存储到location.latitude和location.longitude中 fun getLastLocation(){ ... Log.d("Debug:" ,"Latitude: "+ location.latitude+" Longitude: "+location.longitude) ... } 我有一个内部类,它通过lat和lon值从ope

我有这个getLastLocation函数,它获取当前用户位置并将它们存储到location.latitude和location.longitude中

fun getLastLocation(){
...
Log.d("Debug:" ,"Latitude: "+ location.latitude+" Longitude: "+location.longitude)
...
    }
我有一个内部类,它通过lat和lon值从openweathermap获取天气:

inner class WeatherTask : AsyncTask<String, Void, String>() {

        override fun doInBackground(vararg params: String?): String? {

            var latitude = location.latitude
            var longitude = location.longitude

            var response: String?
            try {
                response =
                    URL("http://api.openweathermap.org/data/2.5/weather?lat=$latitude&lon=$longitude&units=metric&appid=$api").readText(
                        Charsets.UTF_8
                    )
            } catch (e: Exception) {
                response = null
            }
            return response
        }
内部类WeatherTask:AsyncTask(){
重写fun doInBackground(vararg参数:String?):String{
var纬度=位置。纬度
var经度=位置。经度
var响应:字符串?
试一试{
回应=
网址(“http://api.openweathermap.org/data/2.5/weather?lat=$latitude&lon=$longitude&units=metric&appid=$api”).readText(
Charsets.UTF_8
)
}捕获(e:例外){
响应=空
}
返回响应
}

但是它说我的“位置”是一个未解析的引用,它是什么?如何修复它?

您可以将位置作为参数传递到构造函数中:

inner class WeatherTask(var location: Location) : AsyncTask<String, Void, String>() {

location
是外部类的属性吗?@Nicolas它是在getLastLocation()函数中声明的,但我跳过了它这里是完整的代码:啊,你不能在它的函数范围之外使用局部变量。最上面的代码工作得很好!!但是我应该把“WeatherTask(location).execute()放在哪里呢?”?目前我把它放在onCreate中,但它显示“未解析引用:位置”,并要求我创建一个抽象属性,我在这里做什么?@SeriaAti您应该在获得位置后调用AsynTask抱歉,但我不太明白您的意思,我称之为getLastLocation()在setClickListener中的函数,我是否将执行代码放在后面?我已经更新了我的完整代码,你能看一下吗?非常大thank@SeriaAti我的意思是,您应该在成功检索位置数据后,即在
var lastLocation:Loc之后,在回调中调用AsyncTaskation=locationResult.lastLocation
问题已解决,非常感谢!我已经在这个问题上纠缠了两周或更长时间,谢谢!:)希望你晚安!(对我来说是晚上10点)
WeatherTask(location).execute()