0

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.setMinValue(0);
        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!

1 Answers1

0

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.

homerun
  • 19,837
  • 15
  • 45
  • 70
  • Thank you for your answer. Now I know what is the problem based on your last answer you provided. However, I don't know how to put the condition in for loop to get the "00" and "30" values to be displayed in the number picker. Can you help me with that? – Marcel Stiube Feb 19 '20 at 15:20
  • I have managed to resolve the issue. Thank you again for your help @homerun! – Marcel Stiube Feb 19 '20 at 23:41