s.k.paul s.k.paul - 3 months ago 20
Android Question

Volley:Cannot refer to the non-final local variable in android

I have the following method, which submits

http
request using Volley:

private boolean SaveInformationToServer(Information information)
{

RequestQueue queue = Volley.newRequestQueue(this);

StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try{
return true;
}
catch (Exception ex){
return false;
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
return false;
}
});

queue.add(stringRequest);
}


I require this method to return either true or false. But currently it's giving error
void method cannot return a value.
I tried a variable, then I got
cannot refer to the non-final local variable inside an inner class ....


How can I make this method return a
boolean
value to its caller?

Answer

The return type of onResponse is void plus it's a function of an anonymous class so you can't return value from anonymous class to your caller of volley request.

You can create your function can call them on volley response and put your code to execute the result instead of keeping a flag, this will keep your code more structural and readable(you can also set you flags in your onSuccess).

void onSuccess(String response){
// do what you want to do
}
void onError(VolleyError error){
// do what you want to do 
}   
 private void SaveInformationToServer(Information information)
        {

    RequestQueue queue = Volley.newRequestQueue(this);

    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {                           
                        onSuccess(response);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                 onError(error);
            }
        });

        queue.add(stringRequest);
    }