Monday, 12 August 2019

JSONObjectRequest using volley

 
private void createDynamicJson(){
             try {
                    JSONObject rootObject = new JSONObject();
                    rootObject.put(Constants.PARENT_ID, 
                                   AppSharedPreference.getString (MainActivity.this,
                                                AppSharedPreference.PREF_KEY.USER_ID));
                    rootObject.put(Constants.USER_ID, userId);
                  
                    JSONArray jsonArray = new JSONArray();
                    for (int i = 0; i < historyList.size(); i++) {
                        JSONObject object = new JSONObject();
                        HistoryModel model = historyList.get(i);
                        object.put(Constants.QUESTION_ID, model.getQuestionId());
                        object.put(Constants.QUESTION_TYPE, model.getQuestionType());
                        object.put(Constants.ANSWER, model.getAnswerText());
                        jsonArray.put(object);
                    }
                    rootObject.put(Constants.QUESTION_INFO, jsonArray);
                    saveHistory(rootObject);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
 
 }
 
 
private void saveHistory(JSONObject jsonObject) {
    if (AppUtils.getInstance().isNetworkAvailable(this)) {
        AppUtils.getInstance().showProgressDialog(this);
        JsonObjectRequest jsonObjRequest = newJsonObjectRequest(
                Request.Method.POST, RestApi.BASE_URL + "UserHistroy.json",
                jsonObject, response -> {
                    if (response != null) {
                        AppUtils.getInstance().hideProgressDialog(this);
                        try {
                            if (response.get("code").equals(Constants.SUCCESS_CODE_S)) {
                                AppUtils.getInstance().showToast(MainActivity.this,
                                        response.optString("msg"));
                                openActivity();
                            }
                        } catch (Exception e) {
                            e.getMessage();
                        }
                    }
                }, error -> {
                    AppUtils.getInstance().hideProgressDialog(this);
                }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> header = new HashMap<>();
                header.put("authtoken", "");
                return header;
            }
        };
        Application.getInstance().addToRequestQueue(jsonObjRequest);
    } else {
        AppUtils.getInstance().showToast(this, getString(R.string.no_internet));
    }
}

No comments:

Post a Comment