Android Case Expresssions Must Be Constant Expressions

Developing in Eclipse coding Android you will eventually come to a point where you’ll want setting up a library project. You might at this point run into this error when trying to compile. “Case expressions must be constant expressions.

In this case it was due to a switch case. “As of ADT 14, the resource fields (such as R.id.btnnews) are no longer constants when defined in library project. This is necessary to make library projects reusable without recompiling them.

One consequence of this is that you can no longer use the fields directly in switch statements. You must use an if-else chain instead.

Eclipse can automatically convert from a switch statement to an if-else statement. Just place the caret on the switch keyword and invoke Quick Fix (Ctrl-1 on Windows and Linux, Cmd-1 on Mac), then select “Convert ‘switch’ to ‘if-else’.

For more information, see http://tools.android.com/tips/non-constant-fields

To solve this, convert the switch statement into an if-else statement. Place the caret on the switch case and press Ctrl-1 and select “Convert ‘switch’ to ‘if-else’.

Posted in Android, ErrorFix Tagged with: ,