Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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);
}