Reputation: 9
I'm making a sudoku game for Android but I'm having an issue. The game compiles, but once you get to the game screen and press a button the game crashes.
I checked the logcat and these seems to be the errors:
05-04 09:07:41.620: ERROR/AndroidRuntime(325): FATAL EXCEPTION: main
05-04 09:07:41.620: ERROR/AndroidRuntime(325): java.lang.ArrayIndexOutOfBoundsException
05-04 09:07:41.620: ERROR/AndroidRuntime(325): at org.example.fpsudoku.Button.findScreenV(Button.java:59)
05-04 09:07:41.620: ERROR/AndroidRuntime(325): at org.example.fpsudoku.Button.onCreate(Button.java:38)
05-04 09:07:41.620: ERROR/AndroidRuntime(325): at android.app.Dialog.dispatchOnCreate(Dialog.java:307)
05-04 09:07:41.620: ERROR/AndroidRuntime(325): at android.app.Dialog.show(Dialog.java:225)
05-04 09:07:41.620: ERROR/AndroidRuntime(325): at org.example.fpsudoku.Game.showButtonOrError(Game.java:181)
05-04 09:07:41.620: ERROR/AndroidRuntime(325): at org.example.fpsudoku.SudokuScreen.onTouchEvent(SudokuScreen.java:221)
05-04 09:07:41.620: ERROR/AndroidRuntime(325): at android.view.View.dispatchTouchEvent(View.java:3766)
and this is the code that seems to be the problem:
findScreenV();
for (int element : usesquare)
{
if (element != 0)
buttons[element - 1].setVisibility(View.INVISIBLE);
}
setListeners();
}
private void findScreenV()
{
button = findViewById(R.id.button);
buttons[1] = findViewById(R.id.button_1);
buttons[2] = findViewById(R.id.button_2);
buttons[3] = findViewById(R.id.button_3);
buttons[4] = findViewById(R.id.button_4);
buttons[5] = findViewById(R.id.button_5);
buttons[6] = findViewById(R.id.button_6);
buttons[7] = findViewById(R.id.button_7);
buttons[8] = findViewById(R.id.button_8);
buttons[9] = findViewById(R.id.button_9);
Upvotes: 0
Views: 1546
Reputation: 11944
if an array is of length 9 it means you can retrive arr[0] to arr[8],if you try to retrieve arr[9] which is not there you will get an ArrayIndexOutOfBoundsException.
Upvotes: 1
Reputation: 467
In Java when you create the array, at that time u need to give the fix size of that array. like Button[] buttons = new Button[9] and then create the object of that array, like buttons[0] = findViewById(R.id.button_1); Other wise use the arrayList as best solution.
Upvotes: 0
Reputation: 114767
Just a guess - array indexes are zero based. If you need 9 buttons, you'll do
Button[] buttons = new Button[9];
to create the array and
button = findViewById(R.id.button);
buttons[0] = findViewById(R.id.button_1);
buttons[1] = findViewById(R.id.button_2);
buttons[2] = findViewById(R.id.button_3);
buttons[3] = findViewById(R.id.button_4);
buttons[4] = findViewById(R.id.button_5);
buttons[5] = findViewById(R.id.button_6);
buttons[6] = findViewById(R.id.button_7);
buttons[7] = findViewById(R.id.button_8);
buttons[8] = findViewById(R.id.button_9);
to populate it. Addressing buttons[9]
in my example will definitly create an ArrayIndexOutOfBoundsException
Upvotes: 8