I'm trying to take data from a mySQL database and my code take it correctly. The problem is that I have the information in a JsonObjectRequest and out of it, I can't use it. My idea was to use variables to save some of the information I need. Something like this:
val queue=Volley.newRequestQueue(this)
val jsonObjectRequest = JsonObjectRequest(
Request.Method.GET,url,null,
{ response ->
emailGet = response.getString("email")
usernameGet = response.getString("name")
}, { error ->
Toast.makeText(this, error.toString(), Toast.LENGTH_LONG).show()
}
)
queue.add(jsonObjectRequest)
As I said the problem here is that emailGet and usernameGet (variables declared before this code bloc) store the values only inside the JsonObjectRequest, out of it the variables are empty. Example:
val queue=Volley.newRequestQueue(this)
val jsonObjectRequest = JsonObjectRequest(
Request.Method.GET,url,null,
{ response ->
emailGet = response.getString("email")
usernameGet = response.getString("name")
Toast.makeText(this, emailGet, Toast.LENGTH_LONG).show()
}, { error ->
Toast.makeText(this, error.toString(), Toast.LENGTH_LONG).show()
}
)
queue.add(jsonObjectRequest)
Toast.makeText(this, usernameGet, Toast.LENGTH_LONG).show()
Here the Toast will print on the screen only the emailGet content because it's inside the JsonObjectRequest, the Toast that have to print the usernameGet value will not do it.
Looking for information I have found that this problem could be because this function is asynchronous and I found a possible solution in Java that I tried to translate to Kotlin.
val queue=Volley.newRequestQueue(this)
val future : RequestFuture<JSONObject> = RequestFuture.newFuture()
val request = JsonObjectRequest(
Request.Method.GET, url, null, future, future)
queue.add(request)
try{
var response = future.get()
} catch (e : InterruptedException){
} catch (e : ExecutionException){
}
I do not really understand this second code, but it still doesn't working, the response variable is always empty and the program stays in an infinite loop inside that try.
emailGetandusernameGetvariables, you probably want to do it within the callback. Is there a reason why you don't want to/can't do that?