0

i have a web api for registrating students, after i post a student it returns his id, i want to parse this id from json to string and store in variable for later use, the response comes in this form 1234 indicating the user id without "" here is my code

 try {
                            RequestQueue requestQueue = Volley.newRequestQueue(Register.this);
                            String URL = "http://192.168.0.148/WebApplication7/api/users";
                            JSONObject jsonBody = new JSONObject();
                            jsonBody.put("tblRegisteredUsers_UserName", userName.getText().toString().trim());
                            jsonBody.put("tblRegisteredUsers_FirstName", firstName.getText().toString());
                            jsonBody.put("tblRegisteredUsers_SecondName", secondName.getText().toString());
                            jsonBody.put("tblRegisteredUsers_LastName", familyName.getText().toString());
                            jsonBody.put("tblRegisteredUsers_Country", nationality.toString());
                            jsonBody.put("tblRegisteredUsers_MobileNumber", mobileNo.getText().toString());
                            jsonBody.put("tblRegisteredUsers_Email", email.getText().toString());
                            jsonBody.put("tblRegisteredUsers_Nationality", nationality.toString());
                            jsonBody.put("tblRegisteredUsers_Active", "false");
                            jsonBody.put("tblRegisteredUsers_PayType", saved_payment_type.toString());
                            jsonBody.put("tblRegisteredUsers_DraftInfo", saved_payment_type.toString());
                            jsonBody.put("tblRegisteredUsers_AccountStates", "pending");
                            jsonBody.put("tblRegisteredUsers_Password", encrypt(password.getText().toString()));
                            jsonBody.put("tblRegisteredUsers_registrationDate", DateFormat.getDateTimeInstance().format(new Date()).toString());
                            jsonBody.put("tblRegisteredUsers_nickName", userName.getText().toString().trim());
                            jsonBody.put("tblRegisteredUsers_Activeby_FKID", "-1");
                            jsonBody.put("tblRegisteredUsers_Year", "1");
                            jsonBody.put("tblRegisteredUsers_ActivebyPayment", "false");
                            jsonBody.put("tblRegisteredUsers_intensified", contract_Type.toString());


                            final String requestBody = jsonBody.toString();

                            StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {

                                        if (response.equals("success")) {
                                            //login authenticated. Start the next activity of your app
                                            Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_LONG).show();
                                            // Toast.makeText(getApplicationContext(), "registered successfully ", Toast.LENGTH_SHORT).show();


                                        } else {
                                            //login failed. prompt to re-enter the credentials
                                             Toast.makeText(Register.this, "Failed to log In", Toast.LENGTH_SHORT).show();

                                            // Log.i("VOLLEY", response);
                                            Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_LONG).show();
                                        }
                                    }
                            }, new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError error) {
                                    Log.e("VOLLEY", error.toString());
                                }
                            }) {
                                @Override
                                public String getBodyContentType() {
                                    return "application/json; charset=utf-8";
                                }

                                @Override
                                public byte[] getBody() throws AuthFailureError {
                                    try {
                                        return requestBody == null ? null : requestBody.getBytes("utf-8");
                                    } catch (UnsupportedEncodingException uee) {
                                        VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
                                        return null;
                                    }
                                }

                                @Override
                                protected Response<String> parseNetworkResponse(NetworkResponse response) {
                                    try {

    /**
  First you will have to convert the NetworkResponse into a jsonstring.
  Then that json string can be converted into the required java object
   using gson
   **/
                                        addEncodeing2Request(response);
                                        return 
 super.parseNetworkResponse(response);
                                    } catch (UnsupportedEncodingException e) {
                                        e.printStackTrace();
                                        return Response.error(new ParseError(e));
                                    }
                                }
                            };

                            requestQueue.add(stringRequest);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }


                    } else {
                        Toast.makeText(getApplicationContext(), "الرجاء قيول لائحة النظم", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(getApplicationContext(), "password does not match", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(getApplicationContext(), "password is not strong", Toast.LENGTH_SHORT).show();
            }
        }
    });



}

by the way, the return statement in the parse Network method has a compiler error here is the respond

                     {
                     "tblRegisteredUsers_UserPKID": 3034,
                         "tblRegisteredUsers_UserName": "hi21323",
                             "tblRegisteredUsers_Password": null,
"tblRegisteredUsers_FirstName": null,
"tblRegisteredUsers_SecondName": null,
"tblRegisteredUsers_LastName": null,
"tblRegisteredUsers_Country": null,
"tblRegisteredUsers_City": null,
"tblRegisteredUsers_Gender": null,
"tblRegisteredUsers_BirthDate": null,
"tblRegisteredUsers_Education": null,
"tblRegisteredUsers_Job": null,
"tblRegisteredUsers_HomePhone": null,
"tblRegisteredUsers_MobileNumber": null,
"tblRegisteredUsers_FaxNumber": null,
"tblRegisteredUsers_Email": null,
"tblRegisteredUsers_HowYouKnowUS": null,
"tblRegisteredUsers_Nationality": null,
"tblRegisteredUsers_Active": null,
"tblRegisteredUsers_PayType": null,
"tblRegisteredUsers_photo": null,
"tblRegisteredUsers_DraftInfo": null,
"tblRegisteredUsers_AccountStates": null,
"tblRegisteredUsers_registrationDate": null,
"tblRegisteredUsers_nickName": null,
"tblRegisteredUsers_Activeby_FKID": null,
"tblRegisteredUsers_ActivationDate": null,
"tblRegisteredUsers_Year": null,
"tblRegisteredUsers_ActivebyPayment": null,
"tblRegisteredUsers_intensified": null,
"tblRegisteredUsers_Shiping_Address": null,
"tblRegisteredUsers_intensified_Status": null,
"tblRegisteredUsers_ReactivationDateTime": null,
"tblRegisteredUsers_ActivebyPayment_Intensive": null,
"tblRegisteredUsers_ActivationDate_IntensiveChange": null,
"tblRegisteredUsers_Installment": null,
"tblRegisteredUsers_InstallmentActivationDate": null,
"tblRegisteredUsers_Installment_ActivePayment": null,
"tblRegisteredUsers_Hide": null,
"tblRegisteredUsers_Hide_User_FK_ID": null,
"tblRegisteredUsers_Hide_DateTime": null,
"tblRegisteredUsers_Renew_Datetime": null

}

any help would be appreciated

ahmed jallad
  • 161
  • 1
  • 11

1 Answers1

0

If you have a specific Object/Structure of your Json you might want to implement a MyStructureObject.class somewhere and add all those variables to it.

MyStructureObject{
String id;
   public String getIdField(){
      return id;
   }
... // add all other variables of your json structure
}

Than you can use a JSON library like com.google.code.gson (from maven gradle repository) and serialize (or deserialize) a JsonObject from your JsonString.

MySturctureObject instance = new Gson().fromJson(yourJsonString,MyStructureObject.class);
String id = instance.getIdField();

I hope this helps a little :) I already added gson library in my own android java/libgdx application successfully, but maybe you want to use another library instead. It's just a suggestion.

zeg
  • 432
  • 2
  • 9