第一次调用方法时,Volley返回null

时间:2018-04-10 15:18:22

标签: java android http-headers android-volley

我正在尝试使用volley从服务器检索数据,但是当我第一次调用此方法时,我从服务器获得响应,但该方法返回null。如果我第二次打电话给它,我会得到最后的回复。

 public String retrieveDataFromServer(String url, String param, final String token){


        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try{
                            data =  new JSONObject(response).toString();
                        }catch (Exception e){}
                        //Toast.makeText(getApplicationContext(), "wow" + data, Toast.LENGTH_SHORT).show();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        try{
                            data = new JSONObject(error.toString()).toString();
                        }catch (Exception e){}
                        //Toast.makeText(getApplicationContext(), "" +data, Toast.LENGTH_SHORT).show();
                    }
                }) {
            /**
             * Passing some request headers
             */
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                String bearer = "Bearer ".concat(token);
                Map<String, String> headersSys = super.getHeaders();

                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("Content-Type", "application/json; charset=utf-8");
                //headers.put("token", token);

                headersSys.remove("Authorization");
                headers.put("Authorization", bearer);
                headers.putAll(headersSys);
                return headers;
            }
        };
        // Adding request to request queue
        addToRequestQueue(stringRequest);
        //Toast.makeText(getApplicationContext(), "wow" + data, Toast.LENGTH_SHORT).show();

        return data;
}

如何在首次调用方法时获得响应?

1 个答案:

答案 0 :(得分:2)

您可以使用回叫来返回Volley响应:

public void retrieveDataFromServer(final VolleyCallback callback) {
StringRequest strReq = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        callback.onSuccess(response);
    }
}
}}

创建界面:

public interface VolleyCallback{
    void onSuccess(String response);
}

从活动中获得结果:

String yourString = "";
@override
public void onResume() {
    super.onResume();
    retrieveDataFromServer(new VolleyCallback(){
        @Override
        public void onSuccess(String response){
          //Get result from here
             yourString = response;
        }
    });
}