您可以从Kotlin中stringRequest变量之外的截取中获取响应数据吗?
我想在变量之外从我的网站获取截击stringRequest响应您可以从Kotlin中stringRequest变量之外的截取中获取响应数据吗?,kotlin,android-volley,Kotlin,Android Volley,我想在变量之外从我的网站获取截击stringRequest响应 val queue = Volley.newRequestQueue(this) val url = "" // Request a string response from the provided URL. val stringRequest = StringRequest( Request.Method.GET, url, Response.Listener<String> { response
val queue = Volley.newRequestQueue(this)
val url = ""
// Request a string response from the provided URL.
val stringRequest = StringRequest(
Request.Method.GET, url,
Response.Listener<String> { response ->
var obj = JSONObject(response) <-- cant access this variable outside of stringRequest
},
Response.ErrorListener { textView3.text = "That didn't work!" })
stringRequest.body.toString() <-- cant covert null to string
stringRequest.headers.toString() <-- output is {}
//here i want to do something like
if (response == "True") {
//do something
}
val queue=Volley.newRequestQueue(此)
val url=“”
//从提供的URL请求字符串响应。
val stringRequest=stringRequest(
Request.Method.GET,url,
Response.Listener{Response->
var obj=JSONObject(response)此实现的内置方式是异步的,您实际上可以做的是让它看起来更像同步的,如果您在项目中使用协程,您可以使用suspendCoroutine
,请参阅
示例:
suspend fun getData(url: String) = suspendCoroutine<String?> { cont ->
val queue = Volley.newRequestQueue(this)
val stringRequest = StringRequest(Request.Method.GET, url,
Response.Listener<String> { response ->
cont.resume(response)
},
Response.ErrorListener { cont.resume(null) })
queue.add(stringRequest)
}
suspend-fun-getData(url:String)=suspendCoroutine{cont->
val queue=Volley.newRequestQueue(此)
val stringRequest=stringRequest(Request.Method.GET,url,
Response.Listener{Response->
续简历(回复)
},
Response.ErrorListener{cont.resume(null)})
添加(stringRequest)
}
现在可以从response.Listener()中访问响应字符串
编辑:此外,您还可以执行cont.resumeWithException(e)
如果您不想每次使用此函数时都返回可为null的表达式并检查其可为null性,请改为使用。它实际上是异步行为,因为StringRequest没有阻塞
,您无法验证调用是否成功或是否已在下一行中完成。为什么您不能将if调用转到响应侦听器?@AnimeshSahu,因为我的整个项目将依赖于这样的代码片段,能够从响应侦听器外部访问这些数据很好。但是你是说我不能用任何其他方法来做吗?现在你可以调用.body
或.headers
或检查getData()的返回值它将返回Response
@Tiebe Groosman如果你想调用监听器/变量之外的东西,请检查此项。谢谢!我有一个问题。在你使用suspendcorroutine
的线路上,我在Response
类响应所需的一个类型参数上遇到了一个错误
@TiebeGroosman啊,很抱歉,我没有修复它测试了它,所以它发生了,它将与您在侦听器中接收的相同。@TiebeGroosman现在检查一下,我实际上没有意识到错误侦听器没有在lambda中提供任何对象。如果函数返回null,则发生了错误,如果响应调用成功,您可以执行您想要的操作