我有一个JSONArray的JSONObjects,每个都是一个字符串,键是#34; kind"。我试图遍历JSONarray并通过" kind"来组织它们。用于填充SeperatedListAdapter。我想要实现的是这个结构
{
communications[
{ "header":"kind"
communications[
{}
{}
{}
{}
]
}
{ "header":"kind"
communications[
{}
{}
{}
{}
]
}
]
}
我遇到的问题是我为实现此目的而创建的for循环陷入了无限循环,从而导致应用程序崩溃。有谁知道我在哪里出错?
在这里,我的代码我知道它会在循环中陷入困境,因为它运行日志" 1"大约1000次,即使我知道阵中我只传了5件事。
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);
}
}
答案 0 :(得分:1)
在内部for循环的每次迭代中,您将新对象放在newComArray
中。条件a < newComArray.length()
始终满足,因为a
并且数组长度都以相同的速率增长。