I have a number picker for minutes. Initially I set displayed values to 15minute intervals. ie, 0,15,30, 45 which means Min is 1 and max is 4. On user selecting a menu option, I want to dynamically change the same Number picker to have 5 minute intervals which means displayed values will be 0,5,10... 50,55 Min will remain 1 and max will be 12.
It works fine with initial settings for both types. However, I am getting array out of index when I try to modify the max value or displayed values. The issue occurs when changing the characteristics both ways ie 15 to 5 or 5 to 15 minute intervals.
Question is am I doing something wrong or is this not possible at all with number pickers. My sample code is below. thanks.
private void setMinsPicker(String opt) {
String[] mins15 = { "0", "15", "30", "45" };
String[] mins5 = { "0", "5", "10", "15", "20", "25", "30", "35", "40",
"45", "50", "55" };
final String[] mins;
if (opt == "15") {
mins = mins15;
} else {
mins = mins5;
}
numPickerMinutes = (NumberPicker) findViewById(R.id.pMinutes);
int ml = mins.length;
numPickerMinutes.setMinValue(1);
numPickerMinutes.setDisplayedValues(mins);
numPickerMinutes.setMaxValue(ml);
}
It appears to happen because when the NumberPicker detects a change in either the display values or max value it attempts to refresh the view values (i.e. access the display values array). So if you set a display values that is smaller than maxValue - minValue
it'll throw the ArrayOutOfBoundsException
and similarly if you set a max value that is greater than the current it'll throw the exception aw well. If you set the display values to null before changing the min/max values the view will default back to just showing the value and won't access the array at all.
So in your case I'd do something like so...
private void setMinsPicker(String opt) {
String[] mins15 = { "0", "15", "30", "45" };
String[] mins5 = { "0", "5", "10", "15", "20", "25", "30", "35", "40",
"45", "50", "55" };
final String[] mins;
if (opt == "15") {
mins = mins15;
} else {
mins = mins5;
}
numPickerMinutes = (NumberPicker) findViewById(R.id.pMinutes);
int ml = mins.length;
// Prevent ArrayOutOfBoundExceptions by setting
// values array to null so its not checked
numPickerMinutes.setDisplayedValues(null);
numPickerMinutes.setMinValue(1);
numPickerMinutes.setMaxValue(ml);
numPickerMinutes.setDisplayedValues(mins);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With