2

its actually a simple code, cuz of lack of basic I still cant manage to handle this.

After I made a Post JSON Method on my own Api, I get the following response

[{"id":"2"}]

What I'm trying to achieve is that I would like to get the value of this "id" which is "2".

I've tried the following code in my private void method

   private void getUserID() {


    StringRequest stringRequest = new StringRequest(Method.POST,Constants.GET_USER_ID,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();

      try {
         JSONObject  jsonRootObject = new JSONObject(strJson);

         //Get the instance of JSONArray that contains JSONObjects
         JSONArray jsonArray = jsonRootObject.optJSONArray("");

         //Iterate the jsonArray and print the info of JSONObjects
         for(int i=0; i < jsonArray.length(); i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);

            int id = Integer.parseInt(jsonObject.optString("id").toString());
            String idUser = jsonObject.optString("id").toString();


         }
         output.setText(idUser);
      } catch (JSONException e) {e.printStackTrace();}

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
                    }
                })


        {


            @Override
            protected Map<String, String> getParams() throws AuthFailureError {

                Map<String, String> map = new HashMap<>();

                map.put(Constants.KEY_A, username);
                map.put(Constants.KEY_B, password);


                return map;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }

I get it from here.

It's a bit of waste, because I only have one list object in my array, and I thinks for loop is not really important in here.

2
  • strJson is JSONArray instead of JSONObject so do it as :JSONArray jsonArray = new JSONArray(strJson); int _id=jsonArray.getJSONObject(0).getInt("id"); not need to use for-loop if JSONArray contains only single item Commented Jun 28, 2016 at 5:39
  • if you have only one item then remove jsonarray..and make response like this {"id":"2"}..then get id Commented Jun 28, 2016 at 5:42

2 Answers 2

3

replace your try block with following

  try {
             JSONArray  jsonArray = new JSONArray(response);

                JSONObject jsonObject = jsonArray.getJSONObject(0);
                String idUser = jsonObject.getString("id");
                Log.e("id is: ", idUser);

             }
Sign up to request clarification or add additional context in comments.

3 Comments

somewhat android studio wants me to make try catch for all, JSONArray jsonArray = null; try { jsonArray = new JSONArray(response);} catch (JSONException e) {e.printStackTrace();} JSONObject jsonObject = null; try { jsonObject = jsonArray.getJSONObject(0);} catch (JSONException e) {e.printStackTrace(); } String idUser = null; try { idUser =jsonObject.getString("id"); } catch (JSONException e) {e.printStackTrace(); } Log.e("id is: ", idUser);
JSONArray jsonArray = new JSONArray (response); -> AS suggest to make try catch block for it. and soon until String idUser
@GideonStevenTobing You can add the common try catch block as i edited.
1

Try this way you will get

private void makeJsonArrayRequest() {



        showpDialog();

        JsonArrayRequest req = new JsonArrayRequest( delprourl,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d("ress", response.toString());

                        // Parsing json
                        try {

                            for (int i = 0; i < response.length(); i++) {

                                JSONObject person = (JSONObject) response
                                        .get(i);

                                System.out.println("person" + person);

                                //get your id here

                        String id = person.getString("id");
                        Log.e("id: ", id);
                            }




                        } catch (JSONException e) {
                            e.printStackTrace();
                            Toast.makeText(getApplicationContext(),
                                    "Error: " + e.getMessage(),
                                    Toast.LENGTH_LONG).show();
                        }
                        hidepDialog();

                        // notifying list adapter about data changes
                        // so that it renders the list view with updated data
                        //adapter.notifyDataSetChanged();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d("ErrorVolley", "Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_SHORT).show();
                hidepDialog();

            }
        });


        MyApplication.getInstance().addToReqQueue(req, "jreq");
    }


    private void showpDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

    private void hidepDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }

1 Comment

there is an error in .get(i); but anyway, I already find the answer, thanks for your help aditya

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.