Xonal
Xonal

Reputation: 1350

Reading JSON file into Android Application

I have a JSON file with some contacts inside of it and need to create objects out of those contacts to display in a ListView. My problem appears to be accessing the contacts.json file. I don't understand where it should be put so the program can find it. I keep getting a FileNotFoundException. Does anyone know where I should put this file and how I would access it from that location? My current code looks like this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ArrayList<contact> contacts = new ArrayList<contact>();

    String Root_Dir = Environment.getExternalStorageDirectory().getAbsolutePath();
    File file = new File(Root_Dir+"/contacts.json");
    String s = "";
    try {

        Log.d("contact", "1");
        Scanner in = new Scanner(file);
        StringBuilder sb = new StringBuilder();

contacts.json is currently sitting in the assets folder. Obviously, the way I'm looking for it isn't finding it properly.

Upvotes: 0

Views: 170

Answers (1)

Rich
Rich

Reputation: 8202

You want to use getAssets() and use the returned AssetManager to open() your file.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    try {
        InputStream stream = getAssets().open("contacts.json");
        // Do something with the stream
        stream.close();
    } catch (IOException ex) {
        // Handle exception
    }
}

EDIT: If you want to parse your JSON I recomend GSON. First create a class (in the below example Contact) with the same field names as in your JSON.

InputStream stream;
Contact[] contacts = new Gson().fromJson(new InputStreamReader(stream), Contact[].class);

Upvotes: 1

Related Questions