Reputation: 1
I have an ArrayIndexOutofBounds exception in my application. I want to put a previous button in my app. I have 5 elements in my array the button cycles through. How do I make it so when user hits element[0], it will loop back to element[4] and not go to a [-1] causing the exception?
My code is as follows:
mPrevButton = (ImageButton)findViewById(R.id.prev_button);
mPrevButton.setOnClickListener (new View.OnClickListener() {
@Override
public void onClick(View v) {
mCurrentIndex = (mCurrentIndex - 1) % mQuestionBank.length;
mIsCheater = false;
updateQuestion();
}
}
What is the proper way of doing this:
mCurrentIndex = (mCurrentIndex - 1) % mQuestionBank.length;
Upvotes: 0
Views: 361
Reputation: 986
Try to increment in this way:
mCurrentIndex = (mCurrentIndex + mQuestionBank.length - 1)% mQuestionBank.length;
Upvotes: 5
Reputation: 3080
Keep it simple?
if (mCurrentIndex > 0)
mCurrentIndex--;
else
mCurrentIndex = mQuestionBank.length-1;
Upvotes: 5