等待Async Volley请求的结果并将其返回

chi*_*ean 3 java android asynchronous anonymous-function android-volley

下面是一个方法,我试图通过调用getSelf()来检索用户对象.问题是结果始终为null,因为Volley请求在返回结果时尚未完成.我对异步进程有些新意,所以我不确定让方法等待API调用结果返回UserBean对象的最佳方法.谁能给我一些帮助?

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;

}   
Run Code Online (Sandbox Code Playgroud)

Max*_*ysh 11

对于那些从搜索和谷歌来到这个问题的人.

没有理由等待异步请求完成,因为它是异步设计.如果你想使用Volley实现同步行为,你必须使用所谓的期货:

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
Run Code Online (Sandbox Code Playgroud)

请记住,您必须在另一个线程中运行阻塞代码,因此将其包装AsyncTask(否则future.get()将永久阻止).


1Ha*_*aKr 0

您可以使用 VolleyPlus 库来实现此目的https://github.com/DWorkS/VolleyPlus

它有一个叫做 VolleyTickle 和 RequestTickle 的东西。要求是一样的。它是同步请求,一次只有一个请求。