jellyfish
jellyfish

Reputation: 7998

Android: How can I use res/integers.xml values in a switch?

In my application, I just need some global values with nice names. First, what I did was putting them all as "public static final" components into a separate class.

Then I realized that what I did with the global Strings (putting them into res/strings.xml and using them by getString(R.string.string_name)) should also work with integers.

However, I first found out that there's no such thing as getInteger(R.integer.integer_name), but only the rather lengthy way:

Resources r = getResources();
int integer = getInteger(R.integer.integer_name);

Secondly, when I try to use the values in a switch/case expression I only get the message "case expressions must be constant expressions".

So what's the point in using res/integers.xml anyway? I'm just about to put my integers back into some useless class...

Kind regards, jellyfish

Upvotes: 3

Views: 4072

Answers (2)

Hrafn
Hrafn

Reputation: 2946

What have actually done is to create a set of values in either strings.xml or other custom xml files and give them a descriptive names. Those values become static at compile time, every xml value does, and then I can just reference them by their id's.

So in xml I do:

<string name="descriptive_name_that_is_easily_read_in_switch_case">
                     What I put here really doesn't matter</string>

Then in switch/case

switch(someValue){
    case R.id.descriptive_name_that_is_easily_read_in_switch_case:{
      <code>
    }
    break;
}

The beauty of this is that I can remove the enum/static initialization away from the code, making it more readable, and still reuse the values all over the program.

Course there are times when you would like your enums/static values only to be visible in a certain class or method. Then this is not what you would do.

Upvotes: 0

Andreas Dolk
Andreas Dolk

Reputation: 114807

For switch/case expressions we always need constants or enums ( <-- ENUMS!! ) in the case statements. Variables are allowed for the switch parameter, but the case parameters must never change.

So if you need to "store" the case parameters and like nice names, drop integers.xml (doesn't solve your problem) as well as static final public int's - implement an enum instead to model your global values.


Just waited for some details to propose an enum solution ;) Here we go:

public enum Value{ VALUE_ONE(300), VALUE_TWO(501), UNKNOWN(-1);
   private int value;
   private Value(int value) {this.value = value;}

   public int getValue() {
     return value;
   }

   public Value findValue(int value) {
     for (Value v:values()) {
       if (v.value == value)
          return v;
     }
     return Value.UNKNOWN;
}

findValue can be used to get the enum for a number value, the UNKNOWN is an alternative to returning null if we look for a unknown number. Have fun :)

Upvotes: 2

Related Questions