javaandroidnumberpicker

Android number picker using steps


I have managed to create a number picker that loops through 5 to 60 in increments of 5. My only problem is that when I get to 60, the application crashes.

//Number pickers
        int minValue = 5;
        int maxValue = 60;
        int step = 5;

        String[] numberValues = new String[maxValue/minValue];

        for (int i = minValue; i <= maxValue; i+= step)
        {
            numberValues[(i/step)-1] = String.valueOf(i);
        }

        mNumberPicker = (NumberPicker)findViewById(R.id.numberPicker);

        mNumberPicker.setMinValue(0);
        mNumberPicker.setMaxValue(60);

        //mNumberPicker.setValue(20);
        mNumberPicker.setWrapSelectorWheel(false);
        mNumberPicker.setDisplayedValues(numberValues);

There is also an error message in the logcat

java.lang.ArrayIndexOutOfBoundsException: length=12; index=12

I don't understand why as the number has been created successfully so why does the number picker crash when it's chosen?


Solution

  • Change this:

            for (int i = minValue; i <= maxValue; i+= step)
            {
                numberValues[(i/step)-1] = String.valueOf(i);
            }
    

    To this:

    for (int i = 0; i < numberValues.length; i++)
    {
        numberValues[i] = String.valueOf(step + i*step);
    }
    

    Or if you want to keep it confusing (haven't tested but should work):

    for (int i = minValue; i < maxValue; i+= step)
    {
        numberValues[(i/step)-1] = String.valueOf(i);
    }