10

New to Android here, so I apologize if this is a simplistic question.

I am attempting to use a switch based on string resources in my XML. It would look something like this:

switch (myStringVariable) {
    case getResources().getString(R.string.first_string):
         break;
    case getResources().getString(R.string.second_string):
         break;
    case getResources().getString(R.string.third_string):
         break;
    default:
         break;
}

Unfortunately, this won't work. The error that I get is "Constant expression required".

Is there a semi-elegant way to go about this, without having to do something like create 3 String objects and assign the string resources to each object? I feel like I'm missing something obvious, so any assistance would be great!

Thanks :)

user1548103
  • 869
  • 2
  • 12
  • 25

3 Answers3

5

Well, first of all, the version of Java that Android is based on does not support String switch statements, so generally you have to use if/else blocks instead.

EDIT: String switch statements are supported if you use JDK 1.7 and later

I'm not sure what your use case is, but if you have the resource ID of myStringVariable, which is an int, you can do a switch over that:

switch (myStringResId) {
case R.string.first_string:
     break;
case R.string.second_string:
     break;
case R.string.third_string:
     break;
default:
     break;
}
npace
  • 4,218
  • 1
  • 25
  • 35
  • 4
    *not support String switch statements*, that's not true – Blackbelt Apr 09 '15 at 15:00
  • 1
    Oh wow, thanks for pointing that one out. Last time I tried doing a String switch on android was in 2012 before we could compile with JDK 1.7. – npace Apr 09 '15 at 15:06
4

Well, it's not the most elegant way, but you can use if - else if statements instead of switch - case:

if (myStringVariable.equals(getString(R.string.first_string))) {
    // do something
} else if (myStringVariable.equals(getString(R.string.second_string))) {
    // do something
} else if (myStringVariable.equals(getString(R.string.third_string))) {
    // do something
}
yoAlex5
  • 29,217
  • 8
  • 193
  • 205
harryr
  • 41
  • 4
3

You're not missing something Android-related but Java-related instead.

Check this answer about how Java manages the Switch statement:

https://stackoverflow.com/a/3827424/2823516

You'll have to use the non elegant solution you mentioned. But who says is not elegant? Is what you should do, and that makes it elegant.

Community
  • 1
  • 1
Joaquin Iurchuk
  • 5,499
  • 2
  • 48
  • 64