androidindexoutofboundsexceptionandroid-thread

ArrayIndexOutOfBoundsException throws while Thread is working normally


I'm using Thread to set color to a list of ImageView one by one after time of Thread.sleep. It works normally but after few loops of Thread, my app is stop working and throws ArrayIndexOutOfBoundsException.

private Runnable runnable = new Runnable() {

        int position = 0;

        @Override
        public void run() {
            while (true) {
                if (position >= MAX_ITEM) {
                    position = 0;
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        for (int i = 0; i < itemIndicators.size(); i++) {
                            itemIndicators.get(i).setSelected(false);
                        }
                        if (position >= 0){
                            itemIndicators.get(position-1).setSelected(true);
                        }
                    }
                });

                position++;

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    };

My list's size is the same number to MAX_ITEM. Please help me out of this. Thanks so much!


Solution

  • your error is caused by this line

      if (position >= 0){
         itemIndicators.get(position-1).setSelected(true);
       }
    

    you should edit your condition to position > 0 to avoid getting get(-1)