-2

I use Volley library to make API request to Google Places. The response is an object like this:

{
    "html_attributions": [],
    "results": [
        {
          "address":  "Wood Quay, Dublin, Ireland",
          "name":     "Christ Church Cathedral",
          "place_id": "ChIJGw9ASiYMZ0gRy9yiaCZxNZI",
        },
        { ... },
        { ... },
    ],
    "status": "OK"
}

Inside the Response.Listener I need to access the "results" array.
I try to get the JSONArray with name "results" as follows:

    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, API_URL, null,
        new Response.Listener <JSONObject> () {
            @Override
            public void onResponse(JSONObject response) {

                // THE PROBLEM IS HERE - WON'T COMPILE !!!
                JSONArray array = response.getJSONArray("results");
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //
            }
        });

But I see an error: enter image description here

jelhan
  • 6,149
  • 1
  • 19
  • 35

1 Answers1

2

Seems like response.getJSONArray("results"); throws the JSONException. You need to handle that exception by wrapping response.getJSONArray("results"); with a try-catch block.

Something like this:

 try {
    JSONArray array = response.getJSONArray("results");
} catch (org.json.JSONException exception) {
    //  handle the exception
}
Mohammed Siddiq
  • 477
  • 4
  • 16