Volley Response Issue Android

AAA :

I'm parsing a simple JSON response, and it is working when trying to parse the employer name, but it gets to a point where it will eventually crash and say that my 'review' json object, is empty. Here is the response: https://raw.githubusercontent.com/vikrama/feed-json-sample/master/feed.json

And here is how I'm reading it:

private void extractName()
    {
        RequestQueue queue = Volley.newRequestQueue(this);
        JsonObjectRequest request = new JsonObjectRequest(JSON_URL, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONObject gimme = response.getJSONObject("response");
                    JSONArray resultsArray =  gimme.getJSONArray("results");

                    for(int i = 0; i < resultsArray.length(); i++)
                    {
                        JSONObject info = resultsArray.getJSONObject(i);
                        JSONObject review = info.getJSONObject("review");
                        Log.d("COMP NAME", review.getString("employerName"));

                        companyNames.add(review.getString("employerName"));
                    }
                    recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
                    adapter = new CompanyAdapter(MainActivity.this, companyNames);
                    recyclerView.setAdapter(adapter);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("TAG", error.getMessage());
            }
        });

        queue.add(request);
    }

The debug line prints the correct values, then abruptly stops saying "no value for review". I'm pretty confused by this because it seems i'm reading through the data correctly. (use https://jsonformatter.org/json-viewer to better format this json i listed above)

Also, everything else in my recyclerview is set up properly, and the method extractName() is being called in the onCreate() method of my main activity.

Deepak :

This is happening because in some JSON Object you don't have "review" object, so it's throwing your code directly to catch Exception.

In order to overcome this, Please use:-

   if(info.has("review")) {
     JSONObject review = info.getJSONObject("review");
     companyNames.add(review.getString("employerName"));
   }

Instead of:

   JSONObject review = info.getJSONObject("review");
   Log.d("COMP NAME", review.getString("employerName"));
   companyNames.add(review.getString("employerName"));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=296170&siteId=1