Home » Android » android – TimePicker with 30 minute interval not working-Exceptionshub

android – TimePicker with 30 minute interval not working-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment


I am working on a android application and i want to set the timepicker interval to 30 minutes instead of 1 minute by default. This is my code:

private void setTimePickerIntervalZeroThirtyMinutes(TimePicker timePicker) {
        int TIME_PICKER_INTERVAL = 30;
        NumberPicker minutePicker = timePicker.findViewById(Resources.getSystem().getIdentifier("minute", "id", "android"));
        minutePicker.setMaxValue((60 / TIME_PICKER_INTERVAL) + 28);
        List<String> displayedValues = new ArrayList<>();
        for(int i = 0; i < 60; i += TIME_PICKER_INTERVAL) {
            displayedValues.add(String.format("%02d", i));
        minutePicker.setDisplayedValues(displayedValues.toArray(new String[0]));

If I run the above function, it displays the following error:

java.lang.ArrayIndexOutOfBoundsException: length=2; index=30
        at android.widget.NumberPicker.updateInputTextView(NumberPicker.java:1990)
        at android.widget.NumberPicker.setDisplayedValues(NumberPicker.java:1554)

I need to mention that I want to set the min value to 0 and the max value to 30, because otherwise the app won’t save the data correctly to the database. Bot when I do that, it gives me the error that i have shown to you. What am I doing wrong here? Thank you in advance!

How to&Answers:

Your problem is found to be in the loop construction.

  • loop construct : i = 0
  • first loop: i += 30 (i = 30)
  • second loop: i += 30 (i = 60)
  • 60 < 60 = false (exit loop)

therefore your array has only 2 indexes and you trying to access something that does not exist. that is why you get the ArrayIndexOutOfBoundsException. Happy coding.