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 trialMark Leonard
7,428 PointsCodeChallenge 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.
// 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"));
}
{
"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
40,533 PointsYour 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
7,428 PointsMy 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
}
Mark Leonard
7,428 PointsMark Leonard
7,428 PointsMy 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!