0

I am trying to use a NumberPicker to display an array of Strings, but when I try and get the value back of the current String, the value is the integer index value of the String within the array which is the default response.

I have been trying to use NumberPicker.Formatter to get the actual String as a value back as opposed to the integer index value. I have implemented this, but it doesn't seem to be invoked. Could someone please tell me why this is and what I can do to fix it. Thanks in advance.

Here is the code:

final NumberPicker npUnits = (NumberPicker) numberPickerView.findViewById(R.id.numberPicker2);

            npUnits.setMinValue(1);
            npUnits.setDisplayedValues(tableUnitsArray);
            npUnits.setMaxValue(tableUnitsArray.length);
            npUnits.setFormatter(new NumberPicker.Formatter() 
            {
                @Override
                public String format(int value) 
                {
                    ArrayList<String> stringArrayList = (ArrayList<String>) Arrays.asList(tableUnitsArray);
                    String defaultUnits = stringArrayList.get(value);
                    System.out.println("Value formatted result: " + defaultUnits);

                    return defaultUnits;
                }
            });
            npUnits.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
James Meade
  • 1,147
  • 5
  • 22
  • 46
  • Are you providing alternate values for the values? If so, the formatter won't be invoked. – Sujen Mar 18 '14 at 13:56
  • I think that is the problem, because I saw that in the JavaDoc. But what do you mean by alternative values? I set it with a String[] using the setDisplayedValues method. – James Meade Mar 18 '14 at 13:58

3 Answers3

0

NumberPicker allows you to pick your values based on the min and max values you specify. It does not need you to call setDisplayedValues(). NumberPicker uses the String array you specify as a set of alternate values which causes your formatter to be ignored. Try removing the call to setDisplayedValues().

If your values for your NumberPicker are not so straight forward (i.e not from min to max incrementing by 1), then you can transform your values in your formatter to get the desired number.

Sujen
  • 1,614
  • 5
  • 19
  • 25
0

I have found out the answer to my question. NumberPicker.Formatter was the wrong thing that I was doing as I didn't actually need to format anything. I just needed to get the current value from the String[] displayed values.

This is the code that worked for me:

List<String> stringArrayList = (List<String>) Arrays.asList(npUnits.getDisplayedValues());
String defaultUnits = stringArrayList.get(npUnits.getValue() - 1);
James Meade
  • 1,147
  • 5
  • 22
  • 46
0

I found a solution for a few bugs in NumberPicker that works in APIs 18-26 without using reflection and without using setDisplayedValues() here.

Sebastian
  • 2,896
  • 23
  • 36