【问题标题】:Accessing a variable from a function and use it in an inner class从函数访问变量并在内部类中使用它
【发布时间】:2020-10-04 12:50:42
【问题描述】:

我有这个 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
        }

但它说我的“位置”是一个未解决的参考,它是什么?我该如何解决?

【问题讨论】:

  • location 是你外部类的属性吗?
  • @Nicolas 是在 getLastLocation() 函数中声明的,但是我跳过了这里是完整的代码:shorturl.at/glADJ
  • 啊,你不能在其函数范围之外使用局部变量。

标签: android kotlin location global-variables


【解决方案1】:

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

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

称之为:

WeatherTask(location).execute()

【讨论】:

  • 顶级代码完美运行!!但是我应该把“WeatherTask(location).execute()”放在哪里?目前我把它放在 onCreate 但是它显示“未解析的引用:位置”并要求我创建一个抽象属性,我在这里做什么?
  • @SeriaAti 你应该在获取位置后调用 AsynTask
  • 对不起,但我不太明白你的意思我在 setClickListener 中调用 getLastLocation() 函数,我是否将执行代码放在它后面?我已经更新了我的完整代码,你能看一下吗?真的非常感谢
  • @SeriaAti 我的意思是,您应该在成功检索到位置数据后,在回调locationCallback 中调用 AsyncTask,即。在var lastLocation: Location = locationResult.lastLocation 之后
  • 问题解决了,非常感谢!我已经坚持了2周或更长时间,谢谢! :) 希望你有一个美好的夜晚! (对我来说是晚上 10 点)
猜你喜欢
  • 1970-01-01
  • 2018-03-04
  • 2011-06-15
  • 2021-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多