I have a spinner which is populated from an Enum:
public enum Frequencies
{
EVERYDAY("Every day"), EVERYOTHERDAY("Every second day");
private String friendlyName;
private Frequencies(String friendlyName)
{
this.friendlyName = friendlyName;
}
@Override public String toString()
{
return friendlyName;
}
};
The toString() overrides means the spinner displays user friendly names.
The spinner is populated like so:
ArrayAdapter<Frequencies> adapter = new ArrayAdapter<Frequencies>(this, android.R.layout.simple_spinner_item,
Frequencies.values());
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
newAlarmFreqSpinner.setAdapter(adapter);
All of this is working well. When the user chooses a frequency from the spinner, I’d like to use the value to set a long value to represent the interval between alarms in a simple Alarm object. So the value for “Every day” would be the number of seconds in one day.
However, I can’t quite get my head around how to elegantly handle the Frequency object I retrieve from the spinner. My initial thought was to use a switch statement to switch on the displayed string to determine the long value I require, but of course you can’t switch on a string.
I then tried modifying the Frequencies enum so each entry stored its own long value:
EVERYDAY("Every day", 86400), EVERYOTHERDAY("Every second day", 86400 * 2);
private String friendlyName;
public final int intervalInSecs;
private Frequencies(String friendlyName, int intervalInSecs)
{
this.friendlyName = friendlyName;
this.intervalInSecs = intervalInSecs;
}...
But the switch then complains that “case expressions must be constant expressions” (even though I’ve made intervalInSecs final):
Object obj = newAlarmFreqSpinner.getSelectedItem();
switch(((Frequencies)obj).getIntervalInSecs())
{
case Frequencies.EVERYDAY.intervalInSecs: //Java doesn't like this
{
break;
}...
I’m sure I’m making this more difficult than it really is! I’d appreciate any ideas.
Well basically the enum type has it’s associated interval. So you don’t need to switch on the interval, just switch on the enum type: