Android number picker using steps

3k views Asked by At

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?

3

There are 3 answers

3
Roel Strolenberg On BEST ANSWER

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);
}
0
RudyF On

There's another way to tackle the issue that, arguably, may seem more intuitive. It uses the onValueChange method:

@Override
public void onValueChange(NumberPicker np, int oldVal, int newVal) {     
  if (newVal > oldVal) {
     if (newVal < np.getMaxValue())
        np.setValue(newVal+(myStep-1));
     }
     else
        np.setValue(newVal-(myStep-1));
  }
0
youngwoon On

I will replace question's parameter mNumberPicker to np

setDisplayedValues() : The length of the displayed values array must be equal to the range of selectable numbers which is equal to np.getMaxValue() - np.getMinValue() + 1.

So, you have to make numberValues.length() == np.getMaxValue() - np.getMinValue() + 1 true. In your case, make np.setMaxValue(12), not (60) and do like below. It will works.

Briefly, if you want 10~200 arrange in NumberPicker and expected step is 10 :

set minValue = 1, maxValue = 20 and step = 10;

    int minValue = 1;
    int maxValue = 12;
    int step = 5;

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

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

    np.setMinValue(minValue);
    np.setMaxValue(maxValue);

    np.setWrapSelectorWheel(false);
    np.setDisplayedValues(numberValues);

`