嗨伙计我创建一个Android应用程序的登录/注册部分使用Android Volley库。我的应用程序运行良好,但UI和逻辑处于同一个班级。所以,我把它们分成两类。我的应用使用POST方法向我的NodeJS服务器发出请求并获取JSON响应。所以我试图将POST请求函数保留在另一个类中。在返回函数之前等待JSON响应?
分离类后,我在等待响应时出现问题。这是功能;
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];
}
由于响应时间,此函数每次都返回结果[0]为“FREE”。它如何等待响应并根据响应设置结果[0]?我需要知道发出请求时发生了什么。
“它如何根据响应等待响应并设置结果[0]?” - 除非您在自己的后台线程上调用'doWebRequestLogin()',请不要等待响应。换句话说,不要通过等待网络I/O来阻塞主应用程序线程。 – CommonsWare
不幸的是,我在onclick函数中调用了UI上的doWebRequestLogin()。我错过了什么,在UI元素中使用它是一个坏主意? –
为什么这个标记的node.js?这看起来像Java代码。 – jfriend00