Java 等待异步截击请求的结果并返回它
下面是我试图通过调用getSelf()检索用户对象的方法。问题是结果总是空的,因为截击请求在返回结果时还没有完成。我对异步进程有些陌生,所以我不确定让方法等待API调用的结果返回UserBean对象的最佳方式。谁能给我一些帮助吗Java 等待异步截击请求的结果并返回它,java,android,asynchronous,anonymous-function,android-volley,Java,Android,Asynchronous,Anonymous Function,Android Volley,下面是我试图通过调用getSelf()检索用户对象的方法。问题是结果总是空的,因为截击请求在返回结果时还没有完成。我对异步进程有些陌生,所以我不确定让方法等待API调用的结果返回UserBean对象的最佳方式。谁能给我一些帮助吗 public UserBean getSelf(String url){ RpcJSONObject jsonRequest = new RpcJSONObject("getSelf", new JSONArray()); JsonObjectReq
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;
}
公共用户bean getSelf(字符串url){
RpcJSONObject jsonRequest=new RpcJSONObject(“getSelf”,new JSONArray());
JsonObjectRequest userRequest=新的JsonObjectRequest(Request.Method.POST、url、jsonRequest、,
新的Response.Listener(){
@凌驾
公共void onResponse(JSONObject响应){
字符串结果;
试一试{
结果=response.getString(“结果”);
Gson Gson=新的Gson();
java.lang.reflect.Type listType=new-TypeToken(){}.getType();
//如何通过父方法返回此值??
userBean=(userBean)gson.fromJson(结果,列表类型);
}捕获(JSONException e){
e、 printStackTrace();
}
}
},new Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
Log.e(“Error:,Error.toString());
完成();
}
}
);
this.queue.add(userRequest);
返回userBean;
}
您可以使用库VolleyPlus实现这一点
它有一种叫做截击发痒和请求发痒的东西。请求是一样的。这是一个同步请求,一次只有一个请求。对于来自搜索和谷歌的人来说 没有理由等待异步请求完成,因为它在设计上是异步的。如果你想通过截击实现同步行为,你必须使用所谓的未来:
stringurl=”http://www.google.com/humans.txt";
RequestFuture=RequestFuture.newFuture();
StringRequest=新的StringRequest(request.Method.GET、url、future、future)
mRequestQueue.add(请求);
字符串结果=future.get();//这条线会阻塞
请记住,您必须在另一个线程中运行阻塞代码,因此将其包装到
AsyncTask
(否则future.get()
将永远阻塞)。您不应该执行您试图执行的操作。异步处理的原因是,在执行“缓慢”操作时,不会阻塞程序或UI。因此,您的onResponse
应该通知调用者对象可用,然后显示它。如果您需要用户等待,请弹出一个进度对话框,然后在结果可用时将其关闭。同时检查您的响应。它可能是null
。我在截击中想:如果缓存找到它从缓存中获取的内容并响应回UI主线程。这让我成了问题,因为如果JSON被更新,它不会更新数据。此问题的任何解决方案??您可以在请求中使用setShouldCache方法。将false传递给该方法,它将不会缓存结果。
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