user2690146
user2690146

Reputation: 17

Return a result to same level as the call Volley android

I know there are a few very question that are almost identical, however they are just different enough that I can't get my code to work.

I'm using volley to check if a token is valid and want to be able to store the result at the same level as the call i.e. so as if to simulate Boolean isValid = validToken().

This is what I have so far...

Callback interface

interface VolleyCallback {
  void onSuccess(boolean result);
}

Volley function to check token

private void validToken(final String token, final VolleyCallback callback){

        String url = "http://example/api/validate_token";

        JsonObjectRequest jsObjRequest = new JsonObjectRequest
                (Request.Method.POST, url, null, new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        callback.onSuccess(true);
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        callback.onSuccess(false);
                    }
                }){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String,String> headers = new HashMap<String, String>();
                headers.put("Authorization", token);
                return headers;
            }
        };

        //Access the RequestQueue through the singleton class.
        MySingleton.getInstance(this).addToRequestQueue(jsObjRequest);
    }

The function call

Boolean tokenIsValid;
validToken("Bearer eyJhbGciOiJ", new VolleyCallback() {
                @Override
                public void onSuccess(boolean result) {

                }
            });

All I want to be able to do is store the result of the validToken call in the tokenIsValid variable.

Thanks

Upvotes: 0

Views: 237

Answers (1)

user2690146
user2690146

Reputation: 17

In my question I was using a asynchronous volley request and wanting a return value right away. This is wrong, I should have used a synchronous request with a timeout. See this post (Look at the answer about not locking the thread. Asynchronous requests should no be used for things like I was trying to use it for.

Upvotes: 1

Related Questions