PREAMBLE: this question is quite obsolete, it was written when the preferred Android dev environment was Eclipse with the Android plugin.
I had a Java Android project for a while. Today, I've updated the Android dev tools to the Google's latest. And the project broke - I get a bunch of "case expressions must be constant expressions" compilation error messages.
Turns out that the R.java file is being now generated differently. Formerly, it would have a bunch of
public static final int MyID=0x12340000;
statements; now, it looks (after a clean/rebuild) like this:
public static int MyID=0x12340000;
final
is gone. So all switches on resource IDs that I had (and I had a few) are wrong. What happened, please? Is it just me? What's the rationale here? Is it documented anywhere? Can I bring final
back somehow?
This happened about yesterday, when the SDK/ADT 14 got released:
As of ADT 14, resource constants in library projects are no longer final. This is explained in greater detail in http://tools.android.com/tips/non-constant-fields
There's a quickfix available from ADT 14: http://tools.android.com/recent/switchstatementconversion
To quote from the rationale:
When multiple library projects are combined, the actual values of the fields (which must be unique) could collide. Before ADT 14, all fields were final, so as a result, all libraries had to have all their resources and associated Java code recompiled along with the main project whenever they were used. This was bad for performance, since it made builds very slow. It also prevented distributing library projects that didn't include the source code, limiting the usage scope of library projects.
The reason the fields are no longer final is that it means that the library jars can be compiled once and reused directly in other projects. As well as allowing distributing binary version of library projects (coming in r15), this makes for much faster builds.
You could switch over to using If/Else statements and the warning will go away.
Sample:
@Override
public void onClick(final View v) {
//finds which button was pressed
final int buttonView = v.getId();
String current = fromEditText.getText().toString();
if (buttonView == R.id.bA) {
current += getString(R.string.a);
}
}
Just add parentheses:
switch (view.getId()) {
case (R.id.view1):
break;
case (R.id.view2):
break;
}
Google recommends you use if/else conditions
http://tools.android.com/tips/non-constant-fields
To change them automatically you can place the caret on the switch
keyword and press Alt + Enter on Windows (Option + Enter on Mac) and select Replace 'switch' with 'if'
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