0

I would like to use the switch command with choice defined in a resource file but I have the error: error: constant expression required

Do you have any suggestion?

ressource file integers.xml

<integer name="readID">0x21</integer>
<integer name="readRevision">0x22</integer>

java file:

switch (cmd) {
case getResources().getInteger(R.integer.readID):
    break;
case getResources().getInteger(R.integer.readRevision):
    Log.d(TAG, "case revision");
    break;
Twisha Kotecha
  • 1,082
  • 1
  • 4
  • 18
Mich
  • 119
  • 1
  • 8
  • the ids or readId and readVersion resources will change every time your build you app and it's not possible for a switch two have values that could change. You should place this values not on integers.xml but in constants values for exemple or anywhere – SebastienRieu Oct 11 '19 at 13:10

3 Answers3

1

In Java the case part of a switch needs a constant value.

Java expects with getResources().getInteger(R.integer.readID) since it is a method call that the value may change at runtime. See Java switch statement: Constant expression required, but it IS constant for more information.

You may use an if, else if, else construct.

Traendy
  • 1,423
  • 15
  • 17
0

Just define your integers as static constants in a separate file (Constants.java perhaps).

Constants

public class Constants{
public static final int READ_ID = 0x11;
public static final int READ_REVISION = 0x22;
}

Switch

switch (cmd) {
        case Constants.READ_ID:

            break;
        case Constants.READ_REVISION:

            break;
    }
user3783123
  • 544
  • 3
  • 15
0

Try

private int getInt(@IntegerRes int res){
    return context.getResources().getInteger(res);
}

For example:

switch (cmd) {
case getInt(R.integer.readID):
    break;
case getInt(R.integer.readRevision):
    Log.d(TAG, "case revision");
    break;}
Humxa Moghal
  • 122
  • 11