user2182912
user2182912

Reputation: 113

Android:Error - Case expressions must be constant expressions

I have been working on an app, and recently got a new computer. I had to import my existing code into this computer. Now, when I do this I get a few errors in the build path, so I fix them. But now, I get errors in every case in my switch and case. It says: case expressions must be constant expressions.

An example of my code:

case R.id.b3:
    a.putExtra("Green", "green");
    startActivity(a);
    break;
case R.id.b4:
    a.putExtra("Pink", "pink");
    startActivity(a);
    break;

I get the errors on the ids of the button. Everything worked fine on the other computer I used, so I'm not sure why I now get this error. I did google it and I read I should replace them all with an if else statement, but that would be a major pain to replace all my switch and cases, so I'd want to avoid that.

Why this happens on my imported code?

Upvotes: 1

Views: 7725

Answers (4)

twlkyao
twlkyao

Reputation: 14628

This is probably you are using a third_party library, in order to make you develop your application quick and able to use more than one library, the resource id is not defined as final, so you have to use if/else rather than switch/case.

Upvotes: 0

snowCrabs
snowCrabs

Reputation: 785

There is no gurantee that id's are constant in libraries since ADT14 Changes in the tool chain a while back

Upvotes: 0

Robby Pond
Robby Pond

Reputation: 73494

This happens when your resources are defined in a library project. I believe one of the newer versions of the Android plugin requires this based on changes to the way library projects are compiled. The if-else is necessary. The IDE will do it for your automatically. If you highlight the switch keyword and press ctrl-1 you should get an option to make the change automatically.

You can read about it here.

Upvotes: 12

Lena Bru
Lena Bru

Reputation: 13947

Check the activity you are working with , the one that gives you the errors, and look up this line of code in it

import android.R;

delete it! perform clean and everything should work

Upvotes: 0

Related Questions