Egek92 Egek92 - 3 months ago 17
Android Question

Application stops when array index hits below zero

I'm new in android development and currently trying to develop a simple trivia game, I put a previous question button to my app, it works great until the first question, when I click "previous button" on first question app stops working.

mPreviousButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
mCurrentIndex = (mCurrentIndex - 1) % mQuestionBank.length;
updateQuestion();

}
});
updateQuestion();


here is the related code. How can I get out of this situation?

Answer

you need to check that you are currently on first question or not if you are, then just return the method, don't proceed

you can show alert or toast to inform user ...

mPreviousButton.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            if(mCurrentIndex == 0){
                //show toast or alert ...
                return;
            }
            mCurrentIndex = (mCurrentIndex - 1) % mQuestionBank.length;
            updateQuestion();

        }
    });
updateQuestion();
Comments