Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android coding with switch (String)

I'm developing an android app on eclipse, when I try some code like

switch(String){  ...... } 

it give me the following error

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

so I changed the compiler to 1.7, then it give me another error

Android requires compiler compliance level 5.0 or 6.0. Found '1.7' instead. Please use Android Tools > Fix Project Properties. 

So, is there anyway to let switch(String) works in android application? or I have no choice but to use

if(){} else if(){} else if(){} ........ 
like image 434
jing1988ccc Avatar asked Jan 16 '13 20:01

jing1988ccc


People also ask

Can Switch case be used for strings?

Yes, we can use a switch statement with Strings in Java.

Can we pass string in switch case in C?

No you can't.

How do you use a switch statement in Kotlin?

Kotlin does not provide an option to write a switch-case statement; however we can implement the switch-case functionality in Kotlin using the when() function which works exactly the same way switch works in other programming languages.


2 Answers

With the Release of API 19 KitKat you can now do this !!!! This is the change you need for android studio for existing projects. ensure that you are using JDK 1.7 or later and Gradle plugin 0.6.1 or later

android { compileSdkVersion 19 buildToolsVersion "19.0.0"  defaultConfig {     minSdkVersion 7     targetSdkVersion 19 }  compileOptions {     sourceCompatibility JavaVersion.VERSION_1_7     targetCompatibility JavaVersion.VERSION_1_7 } } 
like image 181
Ryan Heitner Avatar answered Oct 11 '22 20:10

Ryan Heitner


switch statement on String objects is a new feature introduced in Java 1.7. Unfortunatelly Android requires version 1.6 or 1.5. This is why you have to forget for some time about such constructions.

You can avoid using if-statements-chain by storing the map of methods which will be executed for certain String: Map<String, Method>. You can always encapsulate Method it with some Handler object. Look here for more info: How to remove large if-else-if chain

and

why-cant-i-switch-on-a-string

like image 33
Adam Sznajder Avatar answered Oct 11 '22 20:10

Adam Sznajder