I\'ve got a very annoying problem with some code throwing an IndexOutOfBoundsException and I really cannot understand why. The logcat points to the \"addTimetableItem\" of the f
The last loop in your for loop runs:
sortedFridayTimes.get(sortedFridayTimes.size())
This will always be out of bounds, because the elements are zero indexed.
For example, if the array size is "5", then you cannot access index "5", because the 5 elements in the array are 0,1,2,3,4
.
You should accept @Tim's or @Graham's answer, this is just an addendum. They're correct about your size()+1
going past the end of the array.
If you're having difficulty using indexes to properly get everything out of the list, you can also try using a for-each loop (depending on the version of the Android SDK you're using). I'm assuming sortedFridayTimes
is a list of class TimetableItem
since you don't specify.
So this:
if(sortedFridayTimes.size()>0){
insertDay("Friday");
for(int i=1; i<sortedFridayTimes.size()+1;i++){
addTimetableItem(sortedFridayTimes.get(i));
}
}
Becomes this:
if(!sortedFridayTimes.isEmtpy()){
insertDay("Friday");
for(TimetimeItem item : sortedFridayTimes){
addTimetableItem(item);
}
}
A little cleaner if you don't actually need to use i
anywhere.
i<sortedFridayTimes.size()+1
You are looping past the last element in the array. Why the +1
?
If there are N
elements in the array, then the elements are from indexes 0
through to N-1
.
So it should be:
for(int i=0; i<sortedFridayTimes.size(); i++) {