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 Adapting Data for Display in a List Filling Our String Array and Creating the Adapter

Stuck in Adapting Data for Display in a List

I have been trying to 3 hours to get the answer to this question:

Some YouTube data in the file 'data.json' has been loaded into a JSONObject named 'jsonData'. Using 'data.json' as your guide, write a 'for' loop that loops through 'jsonVideos'. In each step of the loop, store the value of the 'title' property in the 'titles' array.

My code is below and it doesn't work.

Can someone help me out in this?

/*** This code is an excerpt from a class that extends ListActivity ***/

JSONArray jsonVideos = jsonData.getJSONArray("videos"); String[] titles = new String[jsonVideos.length()];

// Write for loop here! for (int i = 0; i < jsonVideos.length(); i++) { JSONObject posts = jsonVideos.getJSONObject(i); String title = posts.getString("title"); }

2 Answers

Daniel Hartin
Daniel Hartin
18,106 Points

Okay you are not assigning anything into your string array titles. Secondly you have put an assignment of a variable inside your for loop which will not work as you can't create more than one String variable all with the variable name title.

You need to assign the string you get from your JSONData by using an array position. Use the following

titles[i] = posts.getString("title");

and delete the line - String title = posts.getString("title");

This line assigns the result of posts.getString into the titles array at whatever position i is at which obviously increases by 1 with each loop of your code.

Hope this helps.

Thank you Daniel! Your reply was what I needed!