19

I imported a Android project created by someone else into my project as a library module. I get the following error even after cleaning and rebuilding project:

Constant expression required Resource IDs cannot be used in switch statement in Android library

enter image description here

How do I fix this error?

Community
  • 1
  • 1
Gp Master
  • 436
  • 1
  • 4
  • 15
  • Take a look at https://stackoverflow.com/questions/21005205/what-causes-constant-expression-required-errors-for-the-generated-r-id-xxx-val. – ADM Jul 18 '18 at 12:34
  • Replace it by if else statement. and visit this link https://stackoverflow.com/questions/12475166/resource-id-in-android-library-project – Ankita Jul 18 '18 at 12:36
  • Try cleaning your project and build again. – AbhayBohra Jul 18 '18 at 12:50

4 Answers4

16

Your main problem here is that switch statements require constant values as comparators, be it either a literal value e.g. 1, "hello" or a final variable declared at class level. Android R.id values have not been constant since API 14, as stated in that error message, so therefore cannot be used as part of a switch statement.

Your alternative would be to use if else statements as they do not require constant values, like so:

if (v.getId() == R.id.something) {
    // Do something
} else if (v.getId() == R.id.something_else) {
   // Do something else
}
// Repeat however many times required
else {
   // Default value
}
Michael Dodd
  • 10,102
  • 12
  • 51
  • 64
  • 6
    Thanks man. one trick for ease: alt+enter on switch statement to replace it automatically by android studio – Vahid Feb 02 '20 at 11:12
7

You can set a tag for each view and use the tag in the switch case. Something like this:

In your view:

...
android:tag="test" />

In code:

switch(v.getTag()){
    case "test":
    // Do Something
    break;
}
Hamlet Leon
  • 427
  • 3
  • 9
4

Try pressing F4 on one of those items:

public final class R {
    public static final class anim {
        public static int abc_fade_in = 0x7f010001;
        public static int abc_fade_out = 0x7f010002;

They are not declared final.

So you need to use if-else statements not switch.

As an historical note, they used to be final in older versions of Android...

Details here: Switches Suddenly Broken

Elletlar
  • 3,136
  • 7
  • 32
  • 38
2

As the error says, R.id.someId are not final variables (static final int), therefore you cannot directly use switch clause on them. Instead rewrite whole switch with classic

if (v.getId() == R.id.openPictureBtn) {
 ... 
} else if (v.getId() == R.id.openCameraBtn) {
 ... 
}

conditional statements.

Amir Dora.
  • 2,831
  • 4
  • 40
  • 61