Shahensha Khan Shahensha Khan - 1 year ago 74
Android Question

Reading JSON file in Android with API issue

i am new to Android. i have a working JSON reading code in JAVA as below. which save the file as a string and then create the JSON array out of it. i want to do the same in android but it says the error(shown below)

String jsonInput = new Scanner(new File("c:\\patient.txt")).useDelimiter("\\Z").next();
JSONArray ja = new JSONArray(jsonInput);
System.out.println("LENGTH IS____"+ja.length());
String[][] table = new String[ja.length()][4];
for(int y=0;y<ja.length();y++)
JSONObject jb = ja.getJSONObject(y);
String p=jb.getString("priority");
String r=jb.getString("rule_body");
String c=jb.getString("cons");
String b=jb.getString("boolean");
System.out.println("Priority: "+p+"- Rule Body: "+r+"- Consequence: "+c+"- flag: "+b);


which is working fine as intended. I want to do the same in Android(With the text file copied to assets folder) but i get the error that

Call require API 19 and the MIN is 8

i need a help here that how do i sort this out in the working API. I am trying to get the arrays from the JSON file, as i see here most of the example are for JSON objects. The question posted JSONArray not supported before Android API 19 has not mentioned clearly the problem as i stated.

InputStream json= getAssets().open("patient.txt");
JSONArray ja=new JSONArray(json);
System.out.println("LENGTH IS____"+ja.length());
String[][] table = new String[ja.length()][4];

Structure of JSON is


encoded using php encode method.

Answer Source

replace your code with this. this will work fine with lower API too. you are passing InputStream Object as a argument instead you should pass String.

InputStream is = getAssets().open("patient.txt");
int size = is.available();
byte[] buffer = new byte[size];;
String json = new String(buffer, "UTF-8");
JSONArray ja = new JSONArray(json);
System.out.println("LENGTH IS____"+ ja.length());
String[][] table = new String[ja.length()][4];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download