内部类的截击返回

问题描述 投票:0回答:1

我已经成功创建了一个服务器来为我提供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给我错误。而我应该如何返回以便使用异步我可以收到呢?

android class android-volley
1个回答
1
投票

您无法从这样的asynchronous操作获得响应。 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
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.