嗨夥計我創建一個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