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.
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.
Library project resource identifiers are not constant static final int
s, just static int
s.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With