-3

I am trying to get a more specific result than what I am currently getting. Here is my code:

// Request a string response from the provided URL.
    JsonObjectRequest jsObjRequest = new JsonObjectRequest
            (Request.Method.GET, url, (String)null, new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    try {
                        JSONObject city = response.getJSONObject("city  ");
                        mTextView.setText("" + city.toString());
                    }
                    catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            mTextView.setText("That didn't work!");
        }
    });
    mRequestQueue.add(jsObjRequest);
}

Here is a screenshot of what I get in return : enter image description here

More specifically, I'm just trying to get the city name when the JSON value is returned. How can I do this?

mpromonet
  • 11,326
  • 43
  • 62
  • 91
alex23434
  • 389
  • 5
  • 12

1 Answers1

2

Based on the image you posted: response.getJSONObject("city").getString("name");

You have to request a specific field from the JSONObject that way. city.toString() is doing what its supposed to do.

@Override
public void onResponse(JSONObject response) {
    try {
        String cityName = response.getJSONObject("city").getString("name");
        mTextView.setText(city);
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
razzledazzle
  • 6,900
  • 4
  • 26
  • 37
  • This doesn't work at all. In fact, I couldn't use .getString("name") because that's not valid. I had to use .getJSONObject("name") just to get it to compile and it still doesn't deliver the desired result. – alex23434 Jan 16 '16 at 04:00
  • What do you mean? `getString()` is a perfectly valid call on `JSONObject` as documented here. http://developer.android.com/reference/org/json/JSONObject.html – razzledazzle Jan 16 '16 at 04:08
  • Have you tried it? I get an error that says "incompatible types. Required JSONObject found String – alex23434 Jan 16 '16 at 04:10
  • I've rephrased my answer. `getString()` returns a `String`. – razzledazzle Jan 16 '16 at 04:11