java - Android 使用 Volley 从 HTTP 请求中获取响应

标签 java android

我正在尝试重构我的代码。所以我有以下内容:

  1. 主要LoginActivity

      private Boolean userauthenticated;
    
      onTryLogin(){  //login method executed after button click and validation
    
       JSONObject postparams = new JSONObject();
        try {
           postparams.put("username", login_username.getText());
           postparams.put("password", login_password.getText());
           postparams.put("client_secret", ApiHelper.PASSPORT_CLIENT_SECRET);
           postparams.put("grant_type", ApiHelper.PASSORT_GRANT_TYPE);
          postparams.put("client_id", ApiHelper.PASSPORT_CLIENT_ID);
        } catch (JSONException e) {
          e.printStackTrace();
       }
    
     AuthService loginhelper = new AuthService(this);
     userauthenticated = loginhelper.login(loginurl, postparams);
    
     if(userauthenticated){
        //this is always false never executed even when its true
      }
    }
    

所以我的 AuthService 类有

public class AuthService {
     private Context ctx;
     private Boolean userloggedin = false;

      public AuthService(Context cnt){
        ctx = cnt;
     }

   public boolean  login(String loginurl, JSONObject loginparams){

      JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
              (Request.Method.POST, loginurl, loginparams,
                    new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {
                            //set access tokens here
                            Log.i("test","successifully"+response);
                            userloggedin = true;
                        }
                    }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    userloggedin = false;
                }
            }
            );


    // Access the RequestQueue through your singleton class.
    ApiSingleton strngle = new ApiSingleton(ctx);
    strngle.addToRequestQueue(jsonObjectRequest);

    return userloggedin;
  }

}

所以从上面的检查

 if(userauthenticated){
 }

始终返回 false。即使在 AuthService 类 onResponse 中,我也将值设置为 true。 我是 Java 的新手,我刚刚查看了 Volley 库。但是我不知道如何将值从 authservice 类传递到主登录类。

我哪里错了?

最佳答案

问题是,当您这样做时:

userauthenticated = loginhelper.login(loginurl, postparams);

您没有考虑 login() 函数是一个异步函数,因此它将始终返回 false,因为这是此函数返回的默认值。您需要实现一个回调结构。像这样的东西:

public class AuthService {
     private Context ctx;
     private OnLoginCallback callback;
     private Boolean userloggedin = false;

      public AuthService(Context cnt){
        ctx = cnt;
        callback =(OnLoginCallback) cnt;
     }

   public boolean  login(String loginurl, JSONObject loginparams){

      JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
              (Request.Method.POST, loginurl, loginparams,
                    new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {
                            //set access tokens here
                            Log.i("test","successifully"+response);
                            userloggedin = true;
                            callback.onLoginCallback(true);
                        }
                    }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    userloggedin = false;
                      callback.onLoginCallback(false);
                }
            }
            );


    // Access the RequestQueue through your singleton class.
    ApiSingleton strngle = new ApiSingleton(ctx);
    strngle.addToRequestQueue(jsonObjectRequest);

    return userloggedin;
  }

}


interface OnLoginCallback{
    void onLoginCallback(boolean loggedin);
}

然后在您的 Activity 中实现接口(interface) OnLoginCallback 并对 onLoginCallback() 方法使用react。

关于java - Android 使用 Volley 从 HTTP 请求中获取响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49220619/

相关文章:

Java多态方法重写

java - 关于 application.properties 文件和环境变量

java - 如何使用java代码连接远程hadoop hdfs?

android - 在 Android 中手动重绘 ActionBar

java - 使用反射方法设置EditText光标颜色

android - 在 Android 中开发 GUI 的好工具?

Java android listView 搜索

java - 如何在java中播放mp3文件

android - 当 App 崩溃时会发生什么?

java - 如何检查android设备是否可以连接网络?