我正在尝试从android应用向我的远程服务器发出一些POST请求。 我在Kotlin上使用Volley发送JSON数据并接收JSON数据。 从日志中,我可以看到我正在接收JSON数据,但是我的主要功能是从请求完成返回。 这就是为什么它返回null而不是结果的原因。 如何使此功能等待响应?
var result : String? = null
val url = "MY-API-URL"
val post_data = JSONObject()
post_data.put("email_adress", email_adress)
post_data.put("password", password)
val que = Volley.newRequestQueue(this.mContext)
val req = JsonObjectRequest(Request.Method.POST,url,post_data,
Response.Listener
{
response -> result = response.toString()
Log.d("DebugMessageTag", "Real result from server : $result")
// Function does not wait for request to finish.
// It's asynchronous thread, i'll change it to synchronous and fix it. But how???
},
Response.ErrorListener
{
error: VolleyError -> result = "Error $error.message"
}
)
que.add(req)
return result.toString()
// This is returning too early... Thats why it is still null.
答案 0 :(得分:-1)
您必须从响应块中返回。根据您当前的代码,它不会等到收到响应后再尝试对您的代码进行以下更改:
var result : String? = null
val url = "MY-API-URL"
val post_data = JSONObject()
post_data.put("email_adress", email_adress)
post_data.put("password", password)
val que = Volley.newRequestQueue(this.mContext)
val req = JsonObjectRequest(Request.Method.POST,url,post_data,
Response.Listener
{
response -> result = response.toString()
Log.d("DebugMessageTag", "Real result from server : $result")
return result.toString()
// Function does not wait for request to finish.
// It's asynchronous thread, i'll change it to synchronous and fix it. But how???
},
Response.ErrorListener
{
error: VolleyError -> result = "Error $error.message"
return result.toString()
}
)
que.add(req)