Akshay Sharma
Akshay Sharma

Reputation: 13

Not able to change the global value of the given class in kotlin

I want to change the value of idCity of the given class in kotlin

class City_Id(private var cityName: String) {


    var idCity : String? = null

    val url = "https://www.metaweather.com/api/location/search/?query="


    val jsonObjectRequest = JsonArrayRequest(Request.Method.GET, "$url$cityName", null,
            { response ->
                    val cityInfo : JSONObject = response.getJSONObject(0)
                    var cityID : String = cityInfo.getString("woeid")
                    
                    idCity = cityID
                    makeLog(cityID)
                   

                makeLog("from json $idCity")
            },
            { error ->
                    makeLog("$error")

            }

    )

    fun jsonReturn(): JsonArrayRequest {
        return this.jsonObjectRequest
    }


    private fun makeLog(s: String) {
        Log.d("City_Id Activity" , s)

    }

}

The variable "idCity" that I changed locally in "jsonObjectRequest" want to change it globally in class "City_Id". When calling "idCity" from different class it still returning null after changing its value. Thank you in advance

Upvotes: 0

Views: 72

Answers (1)

Rajan Kali
Rajan Kali

Reputation: 12953

The problem is JsonArrayRequest is asynchronous and it won't set the global idCity variable as soon as City_id class instance is created. So if you access the idCity property from else where, you will get null till the request is complete. The better way to handle this is to pass an function as parameter to City_id class and then on response pass invoke the function with value.

Something of below sorts

class City_Id(private var cityName: String, block:(idCity: String) -> Unit) {
    val url = "https://www.metaweather.com/api/location/search/?query="
    val jsonObjectRequest = JsonArrayRequest(Request.Method.GET, "$url$cityName", null,
            { response ->
                    val cityInfo : JSONObject = response.getJSONObject(0)
                    var cityID : String = cityInfo.getString("woeid")
                    makeLog(cityID)
                    block.invoke(cityId)//pass to caller
            },
            { error ->
                    makeLog("$error")

            })

    fun jsonReturn(): JsonArrayRequest {
        return this.jsonObjectRequest
    }
 
    private fun makeLog(s: String) {
        Log.d("City_Id Activity" , s)

    }
}

And at caller side

City_id("name"){idCity ->
    //here you will definitely get the city Id
}

Upvotes: 1

Related Questions