This JSONAray:
"cows": [
{
"age": 972,
"name": "Betty"
"status": "publish",
"sticky": "pregnant"
},
{
"age": 977,
"name"; "Kate"
"status": "publish",
"sticky": "heat"
},
{
"age": 959,
"name": "Julie"
"site_age": 63178480,
"sticky": "Nursing"
},
...
}
that contains 20 objects. What I wanted is this: get 3 random objects out of the 20. And the ages of any of the three won't be a certain number say 961.
Currently this what I am doing:
private void parseCowsReq(JSONObject array) {
try {
for (int i = 0; i < 3; i++) {
int randumNum = getRandomCow(array);
JSONObject jsonObject = array.getJSONObject(randumNum);
String cowName = jsonObject.getString("name");
String cowStatus = jsonObject.getString("status");
Log.d(TAG, "Cow name is " + cowName + "cow Status is " + cowStatus);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private int getRandomCow(JSONArray jsonArray) {
int length = jsonArray.length();
int[] array;
array = new int[length-1];
int rnd = new Random().nextInt(array.length);
return array[rnd];
}
There are of issues with this code.
- I don't know how to ensure that the object gotten in line
JSONObject jsonObject = array.getJSONObject(randumNum);won't have an age of 961 The random number gotten is always 0
Please do you have any idea how this can be done?