1

I was working on an android project using eclipse and suddenly i started to get this error:

Cannot switch on a value of type String for source level below 1.7. Only convertible int values or enum variables are permitted.

I tried every solution in previous similar issues but none of them worked for me...

I have Tried fixing the project and setting the JDK compliance level to 1.7 in both my project and for all project.

I am using ADT Build: v22.2.1-833290 and Eclipse:

String text = mService.getString();
switch (text) {
    case Protocols.REQUEST_SEND_MESSAGE:
        publishProgress("sent");
        break;
    case Protocols.RESPONSE_OK:
        mService.sendMessage("mesasage");   
        publishProgress("sent");  
        break;              
    default:
        break;
}

What's going on?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
T-D
  • 373
  • 8
  • 21

2 Answers2

3

You are trying to use switch / case with String objects, which is only available in Java 1.7 or higher. Android ADT requires Java 1.6. This means you cannot use switch with String construct. Just replace it with if / else.

Replace your code with this.

String text=mService.getString();
if (Protocols.REQUEST_SEND_MESSAGE.equals(text)) {
    publishProgress("sent");
} else if (Protocols.RESPONSE_OK.equals(text)) {
    mService.sendMessage("mesasage");
    publishProgress("sent"); 
}

Another option would be to create an enum and put all Protocol constants into there. Then you will be able to use switch / case with enum values.

sergej shafarenka
  • 20,071
  • 7
  • 67
  • 86
  • Alright thanks a lot. But is there a way to get around this error ? update ? or plugin ? maybe a new Eclipse or ADT version or update ? – T-D Feb 04 '14 at 12:22
  • Yea, i already have it implemented as `if / else` but the code was getting a bit messy because there a lot more of cases so i thought of making it neater by a `switch` case. Thanks for your help. – T-D Feb 04 '14 at 12:25
  • You have to refactor this code to if / else all the time until the time Android starts supporting Java 1.7. No other options are available. – sergej shafarenka Feb 04 '14 at 12:26
  • Another option would be to create an enum from Protocol constants. Then you can use enum values in switch / case. But Android performance guide does not suggest to use enums because they are memory intensive. – sergej shafarenka Feb 04 '14 at 12:29
  • I will look into that too. – T-D Feb 04 '14 at 12:31
2

As the answer below gives more details, switch statement on String objects is a new feature introduced in Java 1.7. Unfortunatelly Android requires version 1.6 or 1.5. :

https://stackoverflow.com/a/14367642/1572408

Community
  • 1
  • 1
Rudi
  • 4,304
  • 4
  • 34
  • 44
  • Thanks, there is a helpful link to check later on in that post [link](http://stackoverflow.com/questions/7349883/how-to-remove-large-if-else-if-chain) – T-D Feb 04 '14 at 12:29