Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
972 views
in Technique[技术] by (71.8m points)

java - Wait for result of Async Volley request and return it

Below is a method in which I am trying to retrieve an user object by calling getSelf(). Problem is that the result is always null since the Volley request has not finished at the time of returning the result. I'm somewhat new to async processes, so I am not sure of the best way to have the method wait for the result of the API call to return the UserBean object. Can anyone give me some help?

public UserBean getSelf(String url){

    RpcJSONObject jsonRequest = new RpcJSONObject("getSelf", new JSONArray());

    JsonObjectRequest userRequest = new JsonObjectRequest(Request.Method.POST, url, jsonRequest, 
        new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {

                String result;
                try {
                    result = response.getString("result");
                    Gson gson = new Gson();
                    java.lang.reflect.Type listType = new TypeToken<UserBean>() {}.getType();

                    //HOW DO I RETURN THIS VALUE VIA THE PARENT METHOD??
                    userBean = (UserBean) gson.fromJson(result, listType);

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
               Log.e("Error:", error.toString());
               finish();
            }
        }
    );

    this.queue.add(userRequest);


    return userBean;

}   
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For those coming to this question from search & google.

There is no reason to wait for an async request to finish, as it is asynchronous by design. If you want to achieve synchronous behaviour using Volley, you have to use so-called futures:

String url = "http://www.google.com/humans.txt";

RequestFuture<String> future = RequestFuture.newFuture();
StringRequest request = new StringRequest(Request.Method.GET, url, future, future)
mRequestQueue.add(request);

String result = future.get(); // this line will block

Keep in mind that you have to run blocking code in another thread, so wrap it into AsyncTask (otherwise future.get() will block forever).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...