Reputation: 6557
I have a JSONArray of JSONObjects in each of which is a string with the key "kind". I'm trying to loop through the JSONarray and organize them by "kind" to use to fill a SeperatedListAdapter. what I am trying to achieve is this structure
{
communications[
{ "header":"kind"
communications[
{}
{}
{}
{}
]
}
{ "header":"kind"
communications[
{}
{}
{}
{}
]
}
]
}
The problem I'm having is the for loop i have created to achieve this gets stuck in an endless loop and thus crashes the application. Does anyone know where I am going wrong with this?
Here's my code I know it gets stuck in a loop as it runs the log "1" about 1000 times even though I know there's only 5 things in the array I'm passing in.
for(int i = 0; i < communicationsFromFile.length(); i++){
JSONObject communication = communicationsFromFile.getJSONObject(i);
Log.v("Communications", "kind = " + communication.getString("kind"));
Log.v("Communications", "newComArray = " + newComArray);
if(newComArray.length() != 0){
Log.v("Communications", "newComArray IsNotempty");
for(int a = 0; a < newComArray.length();a++){
JSONObject itemInArray = newComArray.getJSONObject(a);
JSONArray communicationsForKind = itemInArray.getJSONArray("communications");
Log.v("Communications", "1");
if(itemInArray.getString("header").equals(communication.getString("kind"))){
Log.v("Communications", "Header Exists");
communicationsForKind.put(communication);
itemInArray.put("communications", communicationsForKind);
newComArray.put(itemInArray);
}else{
Log.v("Communications", "Header Does not Exist");
JSONObject addItemInArray = new JSONObject();
JSONArray addArrayToItem = new JSONArray();
addArrayToItem.put(communication);
addItemInArray.put("header", communication.getString("kind"));
addItemInArray.put("communications", addArrayToItem);
newComArray.put(addItemInArray);
}
}
}else{
JSONObject addItemInArray = new JSONObject();
JSONArray addArrayToItem = new JSONArray();
addArrayToItem.put(communication);
addItemInArray.put("header", communication.getString("kind"));
addItemInArray.put("communications", addArrayToItem);
newComArray.put(addItemInArray);
}
}
Upvotes: 0
Views: 39
Reputation: 152807
In each iteration of the inner for loop, you put new objects in the newComArray
. The condition a < newComArray.length()
is always satisfied because a
and the array length both grow at the same rate.
Upvotes: 1