0

I am attempting to parse a json file as part of an android development project. Here is the error message that keeps popping up: W/System.err: java.nio.file.NoSuchFileException: C:/Users/andno/Desktop/AndroidDev2ClimateApp/app/src/main/java/com/example/androiddev2climateapp/ui/home/test.json However, in android studios, the path in the error is supplied as a link, which I can click, leading me to the write file- thus, I don't think the path is wrong. Here is my code:

String first = "C:/Users/andno/Desktop/AndroidDev2ClimateApp/app/src/main/java/com/example/androiddev2climateapp/ui/home/test.json";
try {
    String fileContents = new String((Files.readAllBytes(Paths.get(first))));
    JSONObject json = new JSONObject(fileContents);
    JSONArray widgets = new JSONArray("WidgetArray");
    for(int i = 0; i < widgets.length(); i++){
        int id = widgets.getJSONObject(i).getInt("id");
        System.out.println(id);
    }
} catch(IOException | JSONException e){
    e.printStackTrace();
}

Sorry that the formatting is messed up. I have tried using \ in the path instead of / as well, but it doesn't work. Any help would be greatly appreciated- thanks so much!

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95

1 Answers1

1

You may be able to get this code to work when you're testing, but obviously, there is no C:\Users\andno on your android phone and there never will be.

You're barking up the wrong tree. You don't want to read a file at all.

You want to read a resource from the same place java (or, rather, android) is loading the class file (or whatever passes for class file in android). Which is probably from within a jar or apk or whatnot.

UiMain.class.getResource("test.json")

or

UiMain.class.getResourceAsStream("test.json")

will get you a resource named test.json from the same place that UiMain.class is located (i.e. in the same package, I'm assuming this is class com.example.android.androiddev2climateapp.home.ui.UiMain. The first one as a URL, which you can usually pass to constructors of images and the like, and the second as stream, which you'd need to safely close (try/finally or try-with-resources if android has gotten around to adding that 20 year old java feature already), and which you can turn into a string using various APIs. Probably the JSON API itself can just be fed an inputstream.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72