Android get a response from a HTTP request using Volley

I am trying to refactor my code. So I have the following:

  1. Main 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
      }
    }
    

So my AuthService class has

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;
  }

}

So from the above the check of

 if(userauthenticated){
 }

Always returns false. Even when in the AuthService class onResponse I have set the value to be true. I am new to Java and I just had a look into Volley library. But I can't figure out how to pass the value from authservice class to the main login class.

Where am I going wrong?

1 answer

  • answered 2018-03-11 13:48 Levi Albuquerque

    The problem is, when you do this:

    userauthenticated = loginhelper.login(loginurl, postparams);
    

    You're not considering that the login() function is an async function, therefore it will always return false, because that's the default value for the return in this function. You need to implement a callback structure. Something like:

    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);
    }
    

    Then in your activity you implement the interface OnLoginCallback and react to the onLoginCallback() method.