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

hyunsoo hwang
hyunsoo hwang
3,910 Points

JSON Challenge task 3 of 3

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

Above is the code I wrote for challenge task 3 of 3. But I am getting an error message saying that I had not logged as instructed. I do not see what I have done wrong.

Book title + comma space + page numbers

Could you please help me?


Below is the error message I am getting

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

I tried changing the int to string for 'pages' in data.json but that didn't seem to help. I also tried

JSONArray jsonBooks = jsonData.getJSONArray("books");
for(int i=0;i< jsonBooks.length();i++) {
  JSONObject jsonBook = jsonBooks.getJSONObject(i);
  String title = jsonBooks.getString("title");
  String pages = jsonBooks.getString("pages");
  int page = Integer.parseInt(pages);
  Log.i("CodeChallenge", title + ", " + page);
}

above didn't work either.

I am stuck. Can someone please help me?

1 Answer

Everything is correct except: jsonBooks.getString in both title and pages. Replace it for jsonBook.getString

Edit: I'm assuming it was a typo but just in case it wasn't you are trying to get title and pages of the array and you should be getting it from the element i in the array. Since you called to that element the JSONObject jsonbook as you could've called somethink like JSONObject Book then you have to use the method .getString on that same object name

You are welcome :) Can you mark it as correct if you think it solved your problem?

hyunsoo hwang
hyunsoo hwang
3,910 Points

How do you mark it as correct?

I have no idea. Lol But I thought there was a mark as correct button :P Well vote up at least then hehe :)