-2

having some serious problem when trying to read a local JSON file. I've looked everywhere for many days now and the best and farthest I could get was copying from Faizan's answer. Reading a json file in Android

How come that Android Studio doesn't let me generate the second try-catch code block here?

Help and advice are very much appreciated!!

This is My code

public String loadJSONFromAsset() {
    String json = null;
    try {
        InputStream is = getAssets().open("names.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;
}

String jsonString = loadJSONFromAsset();

try {
    JSONObject json = new JSONObject(jsonString);
    JSONObject jObject = json.getJSONObject("female");
    JSONObject jObject2 = jObject.getJSONObject("adult");
    String name = jObject2.toString();

    }
    catch (Exception e) {
      e.printStackTrace();
    }

 }
Community
  • 1
  • 1
LoveCoding
  • 79
  • 2
  • 13

1 Answers1

1

How come that Android Studio doesn't let me generate the second try-catch code block here?

Simply, because your code is not inside a method.

Doing something like below should solve the error.

public void someMethodIdentifier(){ // doesn't have to be void return type, you know better than me what type you want to return.
    String jsonString = loadJSONFromAsset();
    try {
       JSONObject json = new JSONObject(jsonString);
       JSONObject jObject = json.getJSONObject("female");
       JSONObject jObject2 = jObject.getJSONObject("adult");
       String name = jObject2.toString();
    }
    catch (Exception e) {
       e.printStackTrace();
    }
}

Note - from the looks of the statements that's contained within the try block I think you intended to return some data? if that's the case just replace the void return type with the appropriate return type and return that data.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126