[英]Waiting for JSON response before returning the function?
嗨,大家好,我正在使用Android Volley Library创建一个android应用程序的登录/注册部分。 我的应用程序运行良好,但UI和逻辑处于同一类。 因此,我将它们分为两类。 我的应用程序使用POST方法向我的NodeJS服务器发出请求,并获得JSON响应。 因此,我试图将POST请求功能保留在另一个类中。
分离课程后,我在等待响应时遇到问题。 这是功能;
public String doWebRequestLogin(Context context, boolean checkLoginForm, final Map<String,String> json){
result[0] = "FREE";
this.context = context;
if(checkLoginForm){
StringRequest post = new StringRequest(Request.Method.POST, loginUrl, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
Log.d("Login Response: ",response);
data = response;
res = new JSONObject(data);
if (res.getString(KEY_SUCCESS) != null) {
int success = Integer.parseInt(res.getString(KEY_SUCCESS));
if (success == 1) {
result[0] = "LOGGED";
} else if (success == 0) {
result[0] = "LOGIN ERROR";
} else {
result[0] = "INVALID POST";
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("Response Error", error.toString());
result[0] = "INVALID POST";
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> map = json;
return map;
}
};
VolleyController.getInstance(this.context).getRequestQueue().add(post);
}
return result[0];
}
由于响应时间的缘故,此函数每次都将result [0]返回为“ FREE”。 如何等待响应并根据响应设置result [0]? 我需要知道发出请求时发生了什么。
该请求是异步的,您不得阻塞主线程等待响应。 使方法无效,并在收到响应后使用回调处理响应。
public void doWebRequestLogin(SomeCallback callback, Context context, boolean checkLoginForm, final Map<String,String> json){
[...]
if (res.getString(KEY_SUCCESS) != null) {
int success = Integer.parseInt(res.getString(KEY_SUCCESS));
callback.someMethod(success);
}
}
对于回调:
public interface SomeCallback{
void someMethod(int result); // response received, handle it
}
回调也可以具有返回类型或通用类型,这仅取决于您的需求...
我在onclick函数中的UI上调用doWebRequestLogin()
那么你不希望“等待响应”。 无论网络I / O花费多长时间,这都会冻结您的UI,并且您的用户将不会留下深刻的印象。
而是使用onResponse()
和onErrorResponse()
方法更新UI。
这种通过回调处理结果的异步调用是Android核心事件驱动编程模型的核心。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.