3

下面是一个我试图通过调用getSelf()来检索用户对象的方法。问题在于结果始终为空,因为Volley请求在返回结果时尚未完成。我对于异步流程有点新,所以我不确定让方法等待API调用的结果返回UserBean对象的最佳方式。任何人都可以给我一些帮助吗?等待Async Volley请求的结果并返回它

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; 

} 
+0

你不应该做你想做的事情。异步处理的原因是,在做“慢”的事情时你不会阻止程序或用户界面。所以你的'onResponse'应该通知调用者该对象可用,然后显示它。如果您需要用户等待,请提出进度对话框,然后在结果可用时将其解除。 – 323go

+0

也检查你的回应。它可能是'null'。 –

回答

0

为此,可以使用该库VolleyPlus https://github.com/DWorkS/VolleyPlus

它有一种叫做VolleyTickle和RequestTickle实现。请求是一样的。它是同步请求,并且只有一个请求。

+1

我认为在** VolleyPlus:**如果缓存发现它从缓存中取回并回应到UI主线程。它使我成为问题,因为如果更新JSON,它不会更新数据。任何解决这个问题的方法? –

+0

您可以在请求中使用setShouldCache方法。将false传递给该方法,并且不会缓存结果。 – 1HaKr

9

对于那些从搜索到这个问题&谷歌。

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

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 

请记住,你必须运行在另一个线程阻塞代码,因此它包装成AsyncTask(否则future.get()将永远阻止)。