Use Enums to neatly wrap everything up in.
Using Enums keeps things clean and provides you with a Object Oriented interface without having to persist the data. And by the looks of it, you are using constant values for each of your "flavours" (e.g. Strawberry = 10
).
So, start by creating a "Package" or directory called enums
. We'll keep all your Enums
in there.
Then create a new file in there called Flavour
:
enums/Flavour.java
public enum Flavour {
STRAWBERRY("Strawberry", 10),
CHOCOLATE("Chocolate", 20),
VANILLA("Vanilla", 30);
private String displayString;
private int value;
private Flavour ( String displayString, int value) {
this.displayString = displayString;
this.value = value;
}
@Override
public String toString() {
return displayString;
}
public String displayString() { return displayString; }
public String value() { return value; }
public static Flavour fromDisplayString( String displayString) {
if ( displayString != null ) {
for ( Flavour flavour : Flavour.values() ) {
if ( displayString.equalsIgnoreCase( flavour.displayString ) ) {
return flavour;
}
}
}
throw new IllegalArgumentException("No Flavour with display string " + displayString + " found");
}
public static Flavour fromValue( int value) {
if (value != null) {
for (Flavour flavour : Flavour.values()) {
if (value.equals(flavour.value)) {
return flavour;
}
}
}
throw new IllegalArgumentException("No Flavour with value " + value + " found");
}
}
I'll leave the rest of the adapter stuff up to you to do but the key pieces are this:
Use Flavour.values()
to get the array of Flavours for your Spinner Adapter.
The toString()
will automatically be called when the Spinner is populating so your display string (or whatever you return in that method) will be what's displayed.
When saving the value, you can use this:
( (Flavour) spinner.getSelectedItem() ).value();