如何写一次Google排球请求而不是反复写?

时间:2017-12-22 10:40:58

标签: android json android-volley

朋友们,我正在开发一个学生数据库管理系统App。 下面是为每个用户服务请求向服务器发出请求的代码,服务器发送响应,如Json fromat。

LoginActivity.java

       onCreate(){

              requestQueue = Volley.newRequestQueue(context);

              //making service method call here
              JSONObject json = makeRequest(url,loginJson);

              //printing response given by makeRequest() method
              Log.e("std","-----------------Inside onCreate()----------------------" );
              Log.e("std"," requested json "+json );
       }

     //////

    public JSONObject makeRequest(String url, JSONObject jsonObject){

     JSONObject myjson;

    JsonObjectRequest myReq = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {

            Log.e("std","-----------------Inside onResponse()----------------------" );
            Log.e("std","response \n"+response);

            myJson = new JSONObject(String.valueOf(response))

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            //This code is executed if there is an error.
            error.printStackTrace();
            Log.e("error"," onErrorResponse "+error);
            Toast.makeText(context,"Server Error...",Toast.LENGTH_SHORT).show();
        }
    }){
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json; charset=utf-8");
            return headers;
        }

    };

    requestQueue.add(myReq);


   return myJson;
}

在onResponse监听器中我收到我的回复,如下所示。 但makeRequest方法返回null null JSON。

logcat的

    com.example.stddbsystem E/std:-----------------Inside onResponse()----------------------
    com.example.stddbsystem E/std:{"responseCode": 200,"responseMessage": "Login Success","userId": 1}

    com.example.stddbsystem E/std:-----------------Inside onCreate()----------------------
    com.example.stddbsystem E/std:requested json : null 

1 个答案:

答案 0 :(得分:0)

试试这个:

更改为:

    @Override
    public void onResponse(JSONObject response) {

        myJson =response;

    }

而不是:

      @Override
    public void onResponse(JSONObject response) {


     myJson = new JSONObject(String.valueOf(response))

    }