Thursday, 15 August 2013

java.lang.StackOverflowError. Why am I getting a Stackoverflow exception here

java.lang.StackOverflowError. Why am I getting a Stackoverflow exception here

I have a list of items that are parents and children, displayed in a
hierarchy. I want to toggle their expanded property. so if a parent is
clicked and the parent's children are showing then all of the parents
children will be collapsed and vice versa
Stackoverflow trace points to this line
if (childItem.getItemId() == item.getItemId()) {
hideItemAndDescendants(childItem); //causing stack overflow
}
I under stand that a stackoverflow occurs when a method keeps calling it
self infinitely .but in this case i have a For loop that only loops over
the items list and the list size is only around 10.
public boolean toggleNodeCollapseState(long itemId) {
boolean changed = false; // a flag to determine if anything
collapsed or expanded
for (int i = 0; i < items.size(); i++) {
Item childItem = items.get(i);
if (childItem.getParentItemId() == itemId) {
changed = true;
childItem.setCollapsed(!childItem.isCollapsed());
if (childItem.isCollapsed()) {
hideItemAndDescendants(childItem);
} else {
showDescendants(childItem);
}
}
}
return changed;
}
public void hideItemAndDescendants(Item item) {
item.hide();
for (int i = 0; i < items.size(); i++) {
Item childItem = items.get(i);
if (childItem.getItemId() == item.getItemId()) {
hideItemAndDescendants(childItem);
}
}
}
public void showDescendants(Item item) {
item.hide();
for (int i = 0; i < items.size(); i++) {
Item childItem = items.get(i);
if (childItem.getItemId() == item.getItemId()) {
childItem.show();
if (!childItem.isCollapsed()) {
showDescendants(childItem);
}
}
}
}

No comments:

Post a Comment