Im working myself through the Android Programming 3rd edition book by The big nerd ranch. In Chapter 2 theres a challenge to add previous button to the app. I have added the previous button and it works fine as long as i dont try to previous the first question. I dont know exactly how to loop the button so whenever i previous the first question, it goes by default to the last question. The next button does loop through all the question, however the previous button does not. Im just learning the android environment so im sure this is a simple question. How can i fix my current error?
mNextButton = (Button) findViewById(R.id.next_button);
mNextButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
updateQuestion();
}
});
mPreviousButton = (Button) findViewById(R.id.previous_button);
mPreviousButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
mCurrentIndex = (mCurrentIndex - 1) % mQuestionBank.length;
updatePrevQuestion();
}
});
updateQuestion();
updatePrevQuestion();
}
private void updatePrevQuestion(){
int question = mQuestionBank[mCurrentIndex].getTextResId();
mQuestionTexView.setText(question);
}
private void updateQuestion(){
int question = mQuestionBank[mCurrentIndex].getTextResId();
mQuestionTexView.setText(question);
}
Here is the error Im getting
6-06 19:18:09.158 14727-14727/com.example.dany_user.geo_quiz E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.dany_user.geo_quiz, PID: 14727
java.lang.ArrayIndexOutOfBoundsException: length=6; index=-1
at com.example.dany_user.geo_quiz.QuizActivity.updatePrevQuestion(QuizActivity.java:98)
at com.example.dany_user.geo_quiz.QuizActivity.access$400(QuizActivity.java:11)
at com.example.dany_user.geo_quiz.QuizActivity$5.onClick(QuizActivity.java:87)
at android.view.View.performClick(View.java:6205)
at android.widget.TextView.performClick(TextView.java:11103)
at android.view.View$PerformClick.run(View.java:23653)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)