我已经成功创建了一个服务器来为我提供API。由于我的服务器有许多API,并且我想在我的android项目中使用它们,所以我正在为我的Android应用程序编写两种方法。
一个用于获取,此方法将处理各种GET请求。
public static JSONObject postData(final Context context, String path, Map data)
{
final RequestQueue requstQueue = Volley.newRequestQueue(context);
String url=Util.serverURL+path;
JSONObject res=null;
JsonObjectRequest jsonobj = new JsonObjectRequest(Request.Method.POST,url ,new JSONObject(data),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
res=response;
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context,error.toString(),Toast.LENGTH_SHORT).show();
}
}
){
};
requstQueue.add(jsonobj);
}
这里是无法返回响应的问题。
我如何返回内部类的响应?
分配res给我错误。而我应该如何返回以便使用异步我可以收到呢?
asynchronous
操作完成后,您必须使用回调函数来获取结果。请按照以下步骤操作:
interface
interface VolleyResponseListener {
void onComplete(JSONObject jsonbject);
}
postData
以处理此回调public void postData(final Context context, String path, Map data, VolleyResponseListener callback) {
....
@Override
public void onResponse(JSONObject response) {
callback.onComplete(response);
}
....
}
postData(..., new VolleyResponseListener() {
@Override
public void onComplete(JSONObject jsonbject) {
//you can use jsonbject here
}
});