Android - 等待凌空响应返回 [英] Android - Wait for volley response to return
问题描述
我需要执行一个Volley请求并等待响应解析它并返回它,但不知道如何实现这一点。有人可以帮忙吗?
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?
我现在拥有的是:
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;
}
推荐答案
工厂方法设计模式解决方案:
要从其他方法返回或获取Volley响应,您需要编写一个Callback功能,这很容易使用Interfaces
To return or get Volley response from other method , you need to write a Callback functionality , which is all easy using Interfaces
这个简单的解决方案取自我开发的Android应用程序的MVC架构,具有完整的可用性和关注点分离概念。
This simple solution is taken from my MVC architecture for Android apps developed by me with complete re usability and separation of concern concept.
假设JSONObject是来自服务器的响应
Supposing JSONObject is yours response from server
步骤1)
创建 界面 ServerCallback
package xx.xx.xx.utils;
import org.json.JSONObject;
public interface ServerCallback{
void onSuccess(JSONObject result);
}
步骤2)假设你的 Volley服务器请求方法在控制器类中执行此操作活动
Step 2) Supposing yours Volley server request method is in Controller class do this in yours any Activity
Controller controller = new Controller();
controller.youFunctionForVolleyRequest(email, password, this, loginUrl, new ServerCallback() {
@Override
public void onSuccess(JSONObject response) {
// do stuff here
}
}
);
3)在您的Controller类中,在中调用 ServerCallback 函数inResponse(),只有在完成服务器任务的响应后才会在Activity中执行你的代码!
3) In yours Controller class , call ServerCallback function in inResponse() which will execute yours code in Activity only on response from server- mission accomplished !
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);
}
这篇关于Android - 等待凌空响应返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!