-1

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!

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Bin Ky
  • 11
  • 4
  • Are you sure itemIndicators is size MAX_ITEM? You really should be using itemIndicators.size() instead. And make sure itemIndicators is something that can be accessed asycnhronously safely. – Gabe Sechan May 23 '19 at 15:46
  • yeah, I will keep your words for the next time. Thank you so much for helping xD – Bin Ky May 23 '19 at 16:02

2 Answers2

1

If position is 0 you're accessing item at index -1

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

Remove the -1.

Francesc
  • 25,014
  • 10
  • 66
  • 84
1

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)

ismail alaoui
  • 5,748
  • 2
  • 21
  • 38