Tuesday, March 26, 2013

Setting NumberPicker's setWrapSelectorWheel to true generates exception

Today while working with an Android project, I was puzzled when the following code generated an exception:

// weeks
nums = new String[5];
for (int i = 0; i < nums.length; i++)
nums[i] = Integer.toString(i);

npWeeks.setMinValue(0);
npWeeks.setMaxValue(4);
npWeeks.setWrapSelectorWheel(false);
npWeeks.setDisplayedValues(nums);
npWeeks.setValue(0);

The exception that generated was:

java.lang.IllegalStateException: Range less than selector items count

The following code which behaves exactly the same way, did not throw any exception:
// days
nums = new String[30];
for (int i = 0; i < nums.length; i++)
nums[i] = Integer.toString(i+1);

npDays.setMinValue(1);
npDays.setMaxValue(30);
npDays.setWrapSelectorWheel(true);
npDays.setDisplayedValues(nums);
npDays.setValue(1);

So after digging online, I found the catch: DO NOT SET .setWrapSelectorWheel to 'true' if you have less than 5 items. The mininum > maximum values should be greater than that for this feature to work as NumberPicker widget shows 5 items at a time. When it does not find enough items to wrap, it generates an exception. Happy Coding!

For more information, see this link.


No comments:

Post a Comment