Android / Java Json Objects count
android, java, json
Solution
If you've got your JSON in a String (myString):
JSONArray mArray = new JSONArray(myString);
int id_count = 0;
int devices_count = 0;
int tmp = 0;
for (int i = 0; i<mArray.length(); i++) {
try {
tmp = mArray.getJSONObject(i).getInt("id");
id_count = id_count + 1;
}
catch (JSONException e) {
// If id doesn't exist, this exception is thrown
}
try {
tmp = mArray.getJSONObject(i).getInt("number_of_devices");
devices_count = devices_count + 1;
}
catch (JSONException e) {
// If number_of_devices doesn't exist, this exception is thrown
}
}
myTextView1.text = String.ValueOf(id_count);
myTextView2.text = String.ValueOf(devices_count);
Problem
I'm parsing in android a json api which looks like this: ``` [ { "id":70, "number_of_devices":12, }, { "id":71, "number_of_devices":5, } ] ``` Now I want to get the total count of all devices and display it inside a textview and the total count of all id's and display this inside another textview. Can any one give me an example how to do this, or any tutorial about this ? Thanks for any help