Jarvis
Jarvis

Reputation: 361

How to handle the response of Volley in Android

I use volley in the Android Activity, and make a request and got the response, but I want to handle the response maybe in an another method,but it won't work, what should i do ?

public class TestActivity extends Activity {

RequestQueue queue;

private String result;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    String url = "www.google.com/something/I/need";

    queue = Volley.newRequestQueue(this);

    StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    // Do something with the response
                    Log.i("resp", response);
                    // I want to do sth with the response out of here
                    // maybe like this, let result = response
                    // and see the log at the end of the code
                    // but it failed, what should I do?
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    // Handle error
                    Log.e("error", error.toString());
                }
            });
    queue.add(stringRequest);
    Log.e("result", result);
}

Upvotes: 0

Views: 748

Answers (2)

Francesco Bonn&#236;
Francesco Bonn&#236;

Reputation: 194

The Volley requests are asynchronous, so the program after sending the request, continues execution without waiting for the answer. So the code that processes the result is inserted into the OnResponse method. For more precise help explain why you would like to log out of the method OnResponse

Upvotes: 1

Gil Moshayof
Gil Moshayof

Reputation: 16761

Think about what you're doing: You're creating a StringRequest, then you add it to the request queue, but then you immediately try to check the result. Obviously, this won't work because the request hasn't been processed yet.

Your response will arrive in the onResponse method, and only then you'll be able to do something with it. You can set result = response here, but you'll only be able to see the value when the onResponse is called which could take some time.

Hope this clarifies things.

Upvotes: 0

Related Questions