Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what causes "constant expression required" errors for the generated R.id.xxx values in switch statements?

We've got a multi-project app that we're moving to gradle. The build results in Java compilation errors like:

AFragment.java:159: constant expression required         case R.id.aBtn: 

We've confirmed that the constants reported in errors are in the generated R.java.

One clue is that errors are only for switch values. For example there's no error using findViewById(R.id.aBtn).

also note that the constants are from the main project, not one of the library projects.

for anyone looking to get rid of the errors laalto's suggestion will solve it.

the link he provided, together with the fact that eclipse doesn't show the errors that occur when building with gradle gave me another clue. the R.java generated by eclipse defines the main project constants as 'final' but the gradle generated values are not 'final'. the real solution must be in correcting the gradle build files.

SOLUTION (2014-01-09)

our build.gradle for the app was applying the android-library plugin instead of the android plugin. it was this:

apply plugin: 'android-library'

changing it to this:

apply plugin: 'android'

fixed the problem.

like image 798
user3174822 Avatar asked Jan 08 '14 19:01

user3174822


2 Answers

This happens if you use Resources from a Library project. In that case, the the ids in the R class are not really constants and thus cannot be used in a switch statement.

like image 30
Ridcully Avatar answered Oct 03 '22 05:10

Ridcully


Library project resource identifiers are not constant static final ints, just static ints.

Convert the code that needs to switch on library resource ids to if-else structures.

Further reading: http://tools.android.com/tips/non-constant-fields

like image 166
laalto Avatar answered Oct 03 '22 03:10

laalto