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

Populating a listview from local json data stored in assets folder.

I've been searching online trying to figure out how to do this. I have a simple stats.json file I've copied into an assets folder in android studio:

} "Player": [ { "Name": "Anthony Davis", "Value": "1.19523661501365" }, { "Name": "Stephen Curry", "Value": "1.00267730594504" }, { "Name": "James Harden", "Value": "0.860480054272546" } ] }

First, I made some changes to this data in order to turn it from an array to an object. So if anyone notices any errors it would be appreciated.

Second, I'm trying to get this data to populate a listView in the main activity. My first question is whether or not I need to create a model object like we have been doing in the videos or if I can work with the json data more directly because it's local.

Assuming the former I created this model object:

public class Player {

private String mName;
private Long mValue;

public String getName() {
    return mName;
}

public void setName(String name) {
    mName = name;
}

public Long getValue() {
    return mValue;
}

public void setValue(Long value) {
    mValue = value;
}

}

At this point however, I'm very confused. On stackoverflow I learned that I should read a local json file from my assets folder like this:

public class MainActivity extends Activity {

public String loadJSONFromAsset() {
    String json = null;
    try {

        InputStream is = getAssets().open("stats.json");

        int size = is.available();

        byte[] buffer = new byte[size];

        is.read(buffer);

        is.close();

        json = new String(buffer, "UTF-8");

    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
    return json;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

}

So I am assuming now I should be able to parse the data in stats.json using a jsonObject in the onCreate method, but first I would like to make sure this code is actually reading stats.json. Is there a way I could log something at this point to verify?

Maybe I am trying to learn how to swim at the deep end, but if the above code is on the right track and anyone wants to give me some pointers on how to proceed from here, it would be much appreciated.