Shahensha Khan Shahensha Khan - 3 months ago 11
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);
System.out.println(jb.length());
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);
table[y][0]=p;
table[y][1]=r;
table[y][2]=c;
table[y][3]=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

[{"priority":"1","rule_body":"person(?x),patientid(?y),hasid(?x,?y)","cons":"patient(?x)","boolean":"1"},{"priority":"2","rule_body":"patient(?x),hasbp(?x,high)","cons":"hassituation(?x,emergency)","boolean":"1"},{"priority":"3","rule_body":"patient(?x),hassituation(?x,emergency)","cons":"calldr(emergency)","boolean":"1"},{"priority":"4","rule_body":"patient(?x),calldr(emergency)","cons":"calling_in_dr(emergency)","boolean":"1"},{"priority":"5","rule_body":"patient(?x),calling_in_dr(emergency)","cons":"cured(?x)","boolean":"1"}]


encoded using php encode method.

Answer

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];
is.read(buffer);
is.close();
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];
Comments