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

Working with the loop | Android data from the web

I don't realy understand the loop. Below the code that ive got so far:

String name = jsonData.getString("name"); String publisher = jsonData.getString("publisher"); String language = jsonData.getString("language");

JSONArray jsonBooks = jsonData.getJSONArray("books"); for (int i = 0; <jsonBooks.getJSONObject(i); i++) { Log.i(TAG, "CodeChallange" + title + "," + " " + jsonBooks.length(); }

the error is that > is missing somewhere.

4 Answers

Paul Stevens
Paul Stevens
4,125 Points

Hello,

There are a few errors in the code. The error you are getting is because you have missed the i before the < from the second parameter in the for-loop statement.

for (int i = 0; <jsonBooks.getJSONObject(i); i++) { 

But that won't fix the problem because the for-loop needs to check the length of the jsonBooks array:

for (int i = 0; i < jsonBooks.length(); i++) {

Then we want to make a variable to store one book at a time inside the for-loop

JSONObject jsonBook = jsonBooks.getJSONObject(i);

Then use that variable to get the details of the book and put into a log message

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

The whole code should be as below:

String name = jsonData.getString("name");
String publisher = jsonData.getString("publisher");
String language = jsonData.getString("language");                                 

JSONArray jsonBooks = jsonData.getJSONArray("books");

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

This was a tricky one, I had to watch the video carefully to get it right. :)

Hope this helps,

Paul :)

william parrish
william parrish
13,774 Points

It looks like within your loop, you set the initial value of i by typing "i=0. However after that, you forgot to put the "i" before :

<jsonBooks.getJSONObject.

William, you're right thanks a lot for your help!

Paul,

Thanks for your detailed explanation. I think I understand it now. I appreciate your help.