Reputation: 23
I'm using two buttons to iterate back and forth in an arraylist that contains 12 months, when i reach the last element and press the prevButton the app crashes, this also happens when i go back to the first element and hit the nextButton, how do i fix my if statment?
I have tried to do it with >= and <= but it didn't work
nextButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (i < months.size()) {
Month month = months.get(i);
monthTextView.setText("" + month);
i++;
}
}
});
prevButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (i >= 0) {
Month month = months.get(i);
monthTextView.setText("" + month);
i--;
}
}
});
Upvotes: 0
Views: 61
Reputation: 888
when you reach the last or first index the final value will be -1
or maxsize
of it but when you click the opposite button back the condition is still pass, for example when you already at -1
the next button condition still pass since -1
is < than month.size()
your condition should be something like if i-1 <= 0 and then set i
Edit: I think the person who posted this means that when ( i == months.size() - 1 ) and you say next button, it works fine right then because it gets the last month but then i increases by one, that is, i == months.size() is true now. Then, when you press the prevButton, it is only checked if i >= 0 and not i < months.size(). Thus, the array index is out of bounds now. You should check the index bounds in both button methods.
Upvotes: 1
Reputation: 13571
with the last click you are changing the i
value anyway to -1
or months.size()
by adding/subtracting 1
after accessing last/first element
let us take a look closer on this fragment:
if (i >= 0) { // let us assume that i = 0, we are getting inside
Month month = months.get(i); // you are assigning first element of months, everything is fine
monthTextView.setText("" + month); // some data operation - irrelevant
i--; // anyway you are updating i to [i = -1]
}
// one "next" click later...
if (i < months.size()) { // condition is fine because i = -1
Month month = months.get(i); // oooops tried to access months[-1] - ERROR
monthTextView.setText("" + month);
i++;
}
The same is happening in the second scenario
What you should do - you should update i
value only if current value is strongly > 0
or < month.size() - 1
if (i >= 0) {
Month month = months.get(i);
monthTextView.setText("" + month);
i = (i > 0) ? (i - 1) : 0; // for example like this
}
Upvotes: 1