Listing 3.8 Different ways of logging in Android


// Log a message at “debug” log level
Log.d(TAG, "Current question index: " + mCurrentIndex);
TrueFalse question;
try {
question = mAnswerKey[mCurrentIndex];
} catch (ArrayIndexOutOfBoundsException ex) {
// Log a message at “error” log level, along with an exception stack trace
Log.e(TAG, “Index was out of bounds”, ex);

Three questions:

Was there a change/add somewhere of mAnswerKey? I’m showing/thinking that this should refer to mQuestionBank or that mAnswerKey would have to be set up.

Is this code plug and play other than the mAnswerKey issue?

Where would this code go? I tried a few different places, and got a variety of errors.



Yeah, I believe there are two typos/issues:

  • mAnswerKey should be mQuestionBank
  • mCurrentIndex always has a valid value, so to cause the IndexOutOfBoundsException, you need to add an offset to it to go beyond the array size.

Adding this to updateQuestion() worked for me:

TrueFalse question; try { question = mQuestionBank[mCurrentIndex + 10]; } catch (IndexOutOfBoundsException ex) { android.util.Log.e(TAG, "Index out of bounds", ex); }