Mich
Mich

Reputation: 300

switch case with integer resources

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;

Upvotes: 0

Views: 211

Answers (3)

Traendy
Traendy

Reputation: 1503

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.

Upvotes: 1

Humxa Moghal
Humxa Moghal

Reputation: 132

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;}

Upvotes: 0

user3783123
user3783123

Reputation: 554

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;
    }

Upvotes: 0

Related Questions