Reputation:
I can't believe it isn't answered anywere!
How can I get like the IP from https://ipinfo.io/ip
which would be nothing but a simple string?
This is what I've tried:
var soo = "meh"
val queue = Volley.newRequestQueue(this)
val stringRequest = StringRequest(Request.Method.GET, "https://ipinfo.io/ip",
object : Response.Listener<String> {
override fun onResponse(response: String) {
// Display the first 500 characters of the response string
soo = response
Log.d("letsSee", soo) // THIS WAS CALLED SECOND: the ip
}
}, object : Response.ErrorListener {
override fun onErrorResponse(error: VolleyError) {
soo = "error occurred"
}
})
queue.add(stringRequest)
Log.d("letsSee", soo) // THIS WAS CALLED FIRST: "meh"
Upvotes: 0
Views: 1985
Reputation: 1034
In android all network calls are async and doesn't execute on main thread, Volley follows the same methodology and makes it's network call async, So in your code "Log.d("letsSee", soo)" statement won't wait for Volley to execute network call instead it will get executed
So you have to create callback interface like this
interface ApiResponse{
fun onSuccess(response:String)
fun onError()
}
and then make one function like this
fun getMyIp(apiResponse: ApiResponse) {
val queue = Volley.newRequestQueue(this)
val url = "https://ipinfo.io/ip"
val stringRequest = StringRequest(Request.Method.GET, url,
Response.Listener<String> { response ->
apiResponse.onSuccess(response)
},
Response.ErrorListener {
apiResponse.onError()
}
)
queue.add(stringRequest)
}
and call this getMyIp() function like this
getMyIp(object :ApiResponse{
override fun onSuccess(response: String) {
Log.d("SSB Log", response)
}
override fun onError() {
Log.d("SSB Log", "Error")
}
})
ou can also implement ApiResponse interface at class level
Upvotes: 0
Reputation: 863
this is working
var soo = "meh"
val queue = Volley.newRequestQueue(this)
val stringRequest = StringRequest(Request.Method.GET, "https://ipinfo.io/ip",
com.android.volley.Response.Listener<String> { response ->
soo = response
Log.d("see again", soo)
}, com.android.volley.Response.ErrorListener {
// didn't work
});
queue.add(stringRequest)
Log.d("letsSee", soo)
Upvotes: 1