Java Android - 等待凌空响应返回
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23833977/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android - Wait for volley response to return
提问by JorgeR
I need execute a Volley request and wait for the response to parse it and return it, but have no idea on how to achieve this. Can someone help?
我需要执行一个 Volley 请求并等待响应解析它并返回它,但不知道如何实现这一点。有人可以帮忙吗?
What I have now is this:
我现在拥有的是:
public String getLink() {
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
shortenURL = response.getString("url");
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
});
queue.add(jsObjRequest);
return shortenURL;
}
回答by Quentin Klein
You should probably not return the link in your method.
您可能不应该在您的方法中返回链接。
Volley is doing asynchronoustasks, it means that you can't know when the answer will arrive from your webservice, it could be 10sec or 10min.
Volley 正在执行异步任务,这意味着您无法知道 Web 服务何时会收到答案,可能是 10 秒或 10 分钟。
If you need the string in your function you should probably create a method and call it when you have the result.
如果您需要函数中的字符串,您可能应该创建一个方法并在获得结果时调用它。
Here is an example:
下面是一个例子:
I guess this is what you have
我想这就是你所拥有的
public void getTheLinkAndCallDoSomething(){
String link = getLink();
doSomethingWithTheLink(link);
}
This would work if getLink()
answers in a synchronous way. Volley is not in this case.
如果getLink()
以同步方式回答,这将起作用。Volley 不在这种情况下。
And this is what you can do with Volley:
这就是你可以用 Volley 做的事情:
public void getTheLinkAndCallDoSomething(){
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET,
url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
shortenURL = response.getString("url");
doSomethingWithTheLink(shortenURL);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
});
queue.add(jsObjRequest);
}
In this case, you call the WS to get your url. And as soon as the result is known, you call doSomethingWithTheLink()
在这种情况下,您调用 WS 来获取您的 url。一旦知道结果,你就打电话doSomethingWithTheLink()
Whatever, if you really do want to be synchronousyou can look at this post : Wait for result of Async Volley request and return it
不管怎样,如果你真的想要同步,你可以看看这篇文章:等待 Async Volley 请求的结果并返回它
Also, be aware that waiting for an answer could freeze your app UIand I guess that is not what you want.
另外,请注意等待答案可能会冻结您的应用程序 UI,我想这不是您想要的。
回答by Giru Bhai
you cannot return anydata in your getLink()
method.
Use your code as
你不能在你的getLink()
方法中返回任何数据。使用您的代码作为
String shortenURL = ""; // activity global variable
public void getLink() {
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
shortenURL = response.getString("url");
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
});
queue.add(jsObjRequest);
}
You can also see more info at http://arnab.ch/blog/2013/08/asynchronous-http-requests-in-android-using-volley/
您还可以在http://arnab.ch/blog/2013/08/asynchronous-http-requests-in-android-using-volley/查看更多信息
回答by Divyanshu Jimmy
A Factory method design pattern solution :
工厂方法设计模式解决方案:
To return or get Volley response from other method , you need to write a Callback functionality , which is all easy using Interfaces
要从其他方法返回或获取 Volley 响应,您需要编写回调功能,使用接口很容易做到这一点。
This simple solution is taken from my MVC architecture for Android apps developed by me with complete re usabilityand separation of concernconcept.
这个简单的解决方案取自我为 Android 应用程序开发的 MVC 架构,具有完全的可重用性和关注点分离的概念。
Supposing JSONObject is yours response from server
假设 JSONObject 是您来自服务器的响应
Step 1)
第1步)
Create an InterfaceServerCallback
创建接口ServerCallback
package xx.xx.xx.utils;
import org.json.JSONObject;
public interface ServerCallback{
void onSuccess(JSONObject result);
}
Step 2) Supposing yours Volley server requestmethod is in Controllerclass do this in yours any Activity
步骤 2) 假设您的Volley 服务器请求方法在Controller类中,请在您的任何活动中执行此操作
Controller controller = new Controller();
controller.youFunctionForVolleyRequest(email, password, this, loginUrl, new ServerCallback() {
@Override
public void onSuccess(JSONObject response) {
// do stuff here
}
}
);
3) In yours Controller class , call ServerCallbackfunction in inResponse()which will execute yours code in Activity only on response from server- mission accomplished !
3)在您的控制器类中,在inResponse() 中调用ServerCallback函数, 该函数将仅在来自服务器的响应完成时在活动中执行您的代码!
public void youFunctionForVolleyRequest(final String email , final String password ,final Context context , final String URL, final ServerCallback callback)
{
HashMap<String, String> params = new HashMap<String, String>();
params.put("email", email);
params.put("password", password);
Log.e("sending json",params.toString());
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
URL, new JSONObject(params), new Response.Listener<JSONObject>()
{
@Override
public void onResponse(JSONObject response) {
callback.onSuccess(response); // call call back function here
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//VolleyLog.d("Volley error json object ", "Error: " + error.getMessage());
}
}){
@Override
public String getBodyContentType()
{
return "application/json";
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
回答by Prasanth Perumal
You can do this using the future concept
您可以使用未来概念来做到这一点
RequestFuture<JSONObject> jsonObjectRequestFuture = RequestFuture.newFuture();
JsonObjectRequest request = new JsonObjectRequest(ServiceUrl.BFF_BASE_URL + path, (JSONObject) postBody, jsonObjectRequestFuture, jsonObjectRequestFuture);
requestQueue.add(request);
JSONObject jsonObject = jsonObjectRequestFuture.get(30, TimeUnit.SECONDS);