Android kotlin - get simple string from url

眉间皱痕 提交于 2019-12-11 15:19:52

问题


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"

回答1:


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




回答2:


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)


来源:https://stackoverflow.com/questions/51915104/android-kotlin-get-simple-string-from-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!