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.

Martin Zeitler
  • 1
  • 19
  • 155
  • 216
Gideon Steven
  • 399
  • 4
  • 15
  • `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 – ρяσѕρєя K Jun 28 '16 at 05:39
  • if you have only one item then remove jsonarray..and make response like this {"id":"2"}..then get id – Aditya Vyas-Lakhan Jun 28 '16 at 05:42

2 Answers2

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);

             }
Uma Achanta
  • 3,669
  • 4
  • 22
  • 49
  • 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); – Gideon Steven Jun 28 '16 at 05:56
  • JSONArray jsonArray = new JSONArray (response); -> AS suggest to make try catch block for it. and soon until String idUser – Gideon Steven Jun 28 '16 at 06:03
  • @GideonStevenTobing You can add the common try catch block as i edited. – Zaartha Jun 28 '16 at 06:43
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();
    }
Aditya Vyas-Lakhan
  • 13,409
  • 16
  • 61
  • 96