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 Build a Blog Reader Android App Getting Data from the Web Parsing Data Returned in JSON Format

Dillon Shaw
Dillon Shaw
6,400 Points

Why is my for loop on the JSONChallenge code challenge not working?

I get the error that the loop should run twice and call getJSONObject(int i) each time. Not seeing anything in my code that wouldn't do this..

for (int i = 0; i < jsonBooks.length(); i++) {
    JSONObject jsonBook = jsonBooks.getJSONObject(i);
    String title = jsonBook.getString("title");
    String pages = jsonBook.getString("pages");
    Log.i("CodeChallenge", "Book " + title + "," + pages);
}

4 Answers

Tom Simkins
Tom Simkins
2,486 Points

I got stuck on that for a while your missing a section of code before the for statement that defines some important things for a start the log is Log.i("CodeChallenge", title + ", " + pages) Check the json file again and the strings you are getting from the array of books you need a little more code before the for statement. :) hope this puts you on the right track.

Dillon Shaw
Dillon Shaw
6,400 Points

Ah thanks I forgot to pull the book array.

Tom Simkins
Tom Simkins
2,486 Points

Yeah that's what I messed up on XD took me ages to figure out that challenge is a stinker

Joseph Kato
Joseph Kato
35,340 Points

I think the issue is that this:

Log.i("CodeChallenge", "Book " + title + "," + pages);

Should actually be:

Log.i("CodeChallenge", title + ", " + pages);
Tom Simkins
Tom Simkins
2,486 Points

Yep :) I think there might be another issue also

Harry James
Harry James
14,780 Points

Hello, It seems the last line of your code was incorrect. I have checked this through the Code Challenge and it passed:

for (int i = 0; i < jsonBooks.length(); i++) {
 JSONObject number = jsonBooks.getJSONObject(i);
  String title = number.getString("title");
  String pages = number.getString("pages");
  Log.i("CodeChallenge", title + ", " + pages);
}