Search code examples
androidkotlinlocationglobal-variables

Accessing a variable from a function and use it in an inner class


I have this getLastLocation function which gets the current user location and store them into location.latitude and location.longitude

fun getLastLocation(){
...
Log.d("Debug:" ,"Latitude: "+ location.latitude+" Longitude: "+location.longitude)
...
    }

And I have this inner class which gets the weather from openweathermap via the lat and lon values:

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
        }

But it says my "location" is an unresolved reference, what is it? How do I fix that?


Solution

  • You can pass the location as parameter in the constructor:

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

    call it as:

    WeatherTask(location).execute()