Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android Android Lists and Adapters (2015) Updating the Data Model Using JSONArray

Mark Leonard
Mark Leonard
7,428 Points

CodeChallenge java.lang.nullpointerexception

I am getting a java.lang.nullpointerexception with this code. I experimented with casting the object explicitly although I don't think I needed to. Why would I be getting this exception? From looking online it looks like it might be because I have the tag "title" wrong, but it looks correct.

CodeChallenge.java
// JSONObject 'jsonData' was loaded from data.json\
JSONArray jsonShows = jsonData.getJSONArray("shows");
for(int i = 0; i<= jsonShows.length(); i++){
  JSONObject show = (JSONObject)jsonShows.getJSONObject(i);
  Log.i("CodeChallenge", show.getString("title")); 
}
data.json
{
    "name":"Netflix Playlist",
    "shows":[
        {
            "title":"Doctor Who",
            "season":8,
            "episode":3
        },
        {
            "title":"Arrow",
            "season":1,
            "episode":10
        },
        {
            "title":"Portlandia",
            "season":4,
            "episode":5
        }
    ]
}

2 Answers

Dan Johnson
Dan Johnson
40,532 Points

Your cast is fine, though as you gussed, not necessary (getJSONObject returns the type JSONObject).

What's actually happening is you're going out of bounds on the JSONArray. Since arrays are zero based you'll want to use:

i < jsonShows.length()

Instead.

I'm not sure why the challenge is reporting this as a NullPointerException, it should be a JSONException.

Mark Leonard
Mark Leonard
7,428 Points

My mistake, I just left a comment. I work in vb.net and I am so used to length being a valid last index of the array.

Thanks so much!

Mark Leonard
Mark Leonard
7,428 Points

My mistake. I should have set the for loop to < only, not <=. (I work vb.net where that is how you do it.)

for(int i = 0; i<jsonShows.length(); i++) {
//code
}