Volley - http request in blocking way

前端 未结 5 1388
时光说笑
时光说笑 2020-12-09 04:13

I\'m learning how to use Google Volley these days. It\'s very convenient for fast networking. It seems that all the requests are running in background in Volley. For example

5条回答
  •  执笔经年
    2020-12-09 05:02

    I couldn't get RequestFuture working so I just used a callback listener like Makibo suggested. I've no idea why he was downvoted, this is probably the best solution for the original common problem of different Volley requests that all depends on an initial Login or something. In this example, I want to upload a photo but first I've to check if user is logged in or not. If not, I've to login and then wait for success before uploading the photo. If already logged in, just go straight to uploading the photo.

    Here's my sample code:

    // interface we'll use for listener
    public interface OnLoginListener {
        public void onLogin();
    }
    
    public void uploadPhoto(final String username, final String password, final String photo_location) {
        // first setup callback listener that will be called if/when user is logged in
        OnLoginListener onLoginListener=new OnLoginListener() {
            @Override
            public void onLogin() {
                uploadPhotoLoggedIn(photo_location);
            }
        };
        // simplistic already logged in check for this example, just checking if username is null
        if (loggedInUsername==null) {
            // if it null, login and pass listener
            httpLogin(username, password, onLoginListener);
        } else {
            // if not null, already logged in so just call listener method
            onLoginListener.onLogin();
        }
    }
    
    public void httpLogin(String username, String password, final OnLoginListener onLoginListener) {
        StringRequest loginRequest = new StringRequest(Request.Method.POST, "https://www.example.com/login.php", new Response.Listener() { 
            @Override
            public void onResponse(String txtResponse) {
                Log.d("STACKOVERFLOW",txtResponse);
                // call method of listener after login is successful. so uploadPhotoLoggedIn will be called now
                onLoginListener.onLogin();
            } }, 
            new Response.ErrorListener() 
            {
                @Override
                public void onErrorResponse(VolleyError error) {
                    // TODO Auto-generated method stub
                    Log.d("VOLLEYERROR","error => "+error.toString());
                }
            }
                ) {
        };    
        // Just getting the Volley request queue from my application class (GetApplicatio.java), and adding request
        GetApplication.getRequestQueue().add(loginRequest);
    }
    

提交回复
热议问题