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 :)

2
  • 4
    the if else if construct Commented Apr 9, 2015 at 14:57
  • 2
    Assigning the string objects these values still doesn't work, right? The values are decided at run time, not compile time? Commented Jun 9, 2015 at 20:27

3 Answers 3

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

not support String switch statements, that's not true
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.
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
}

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.