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

Bianca Power
Bianca Power
1,249 Points

Help with Getting Data From the Web final challenge

Hi,

I'm having trouble with this, would really appreciate any help!

Here is my code:

// JSONObject 'jsonData' was loaded from data.json

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 < jsonData.length(); i++){ JSONObject jsonStuff = jsonData.getJSONObject(i); String title = jsonStuff.getString("title"); String pages = jsonStuff.getString("pages"); Log.i("CodeChallenge", title + ", " + pages); }

And this is the error I am getting:

JavaTester.java:59: getJSONObject(java.lang.String) in org.json.JSONObject cannot be applied to (int) JSONObject jsonStuff = jsonData.getJSONObject(i); ^ 1 error

1 Answer

Your for loop is looping through the wrong thing.

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

In your condition, you had jsonData.length() intead of jsonBooks.length(), and within the body of the loop, the line

JSONObject jsonStuff = jsonBooks.getJSONObject(i);

was also trying to access jsonData as a whole instead of the jsonBook found at the index given. :) You gave a .length(); and index value to jsonData, and because it is not a JSONArray, it had no idea what to do with it. The array is always what you want to pass an index to.

When tested, the above for loop gives a successful answer.