I am trying to add content of a json file to an arraylist. I have done this a couple of times before but I cannot figure out what is wrong in this particular case that I cannot add anything to the arraylist.
So I have a :
private List<Person> persons = new ArrayList<Person>();
and this is how I load the json file from assets folder (from this answer):
public String loadJSONFromAsset() {
String json = null;
try {
// json file name
InputStream is = this.getAssets().open("file.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;
}
and to write:
public void writeJson(){
try {
JSONObject obj = new JSONObject(loadJSONFromAsset());
JSONArray response = new JSONArray(loadJSONFromAsset());
for (int i = 0; i < response.length(); i++) {
Person person = new Person();
JSONObject jo_inside = response.getJSONObject(i);
Log.d(TAG, jo_inside.getString("firstName"));
//Add values in `ArrayList`
person.setName(obj.getString("firstName"));
person.setAge(obj.getString("age"));
person.setPhoto(obj.getInt("id"));
// Add to the array
persons.add(person);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
When I try to print the content of persons array for testing purposes, I get nothing using the above method. However, if I insert a person like this :
persons.add(new Person("John", "23 years old", 1));
then it will be added to the array.
I think there is a minor mistake somewhere but I can't find the solution.