lundi 25 mai 2015

Load External JSON file in Java Android

i just started learning Java. I'm currently working on a small app that retrieves data from a .JSON file, and stores it into a SQLite database.

I'm trying to open a .JSON file and store it as a JSONObject. Here is my code for reading a JSON file.

private JSONObject readFile(String path)
{
    StringBuilder sb = new StringBuilder();
    try {
        FileReader in = new FileReader(new File(path));
        int b;
        while((b = in.read()) != -1) {
            sb.appendCodePoint(b);
        }
        in.close();

        return new JSONObject(sb.toString());
    }
    catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return null;
}

My JSON files are stored in : app\src\main\java\proj\bb\database\jsonFiles Im currently calling the readFile method like this:, but it throws a NullPointer. (DatabaseOperations is the classname).

    JSONObject jsonFile = readFile(DatabaseOperations.class.getResource("filename.json").toString());
    JSONArray arr = jsonFile.getJSONArray("someArray");

I also tried this without succes:

  JSONObject jsonFile = readFile("jsonFiles/filename.json").toString());
    JSONArray arr = jsonFile.getJSONArray("someArray");

So my question is, what needs to be the path i need to pass as an argument? Or am I doing something else wrong?

Thanks in advance !

Aucun commentaire:

Enregistrer un commentaire