Search code examples
androidjsongoogle-apidrawableandroid-bitmap

Android: json response, google api and getting image from url


I'm using google books api to get some data as json response. in the response, there are JSONArrays, each element is a book and it contains data about it. the problem is the elements should be symmetric when it comes to the data they contain. in other words, each element should contain a title, authors, book cover url, rating and so on. and when a book doesn't contain ,for example, a rating, this value should exist and be empty but it doesn't exist at all for that element so in the for loop it throws an exception

the exception message

so what should i do to avoid such a problem and i do need that data even if it's empty.


the other part is there is a url for the cover of the book provided in the response. i want to get that image. i tried both top answers in this link and non of them seemed to work.


Solution

  • Try to use optJSONObject instead of getJSONObject to get JSONObject.
    Note: getJSONObject will through error if the object don't have the key, but optJSONObject will just return null if the object don't have value

    JSONArray array = null;// your array
                for (int i = 0; i < array.length(); i++) {
                    JSONObject jsonObject = array.optJSONObject(i);
    
                    if(jsonObject == null) {
                        continue;
                    }
    
        //            JSONObject ratingObject = jsonObject.getJSONObject("rating"); // Dont use this
                    JSONObject ratingObject = jsonObject.optJSONObject("rating");
    
                    if(ratingObject != null) {
                        // Do someting here
                    }
                }
    

    For Image loading you can use Glide lib it may help you.