Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using string from resource XML in Switch?

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

like image 467
user1548103 Avatar asked Apr 09 '15 14:04

user1548103


2 Answers

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
}
like image 116
harryr Avatar answered Oct 14 '22 05:10

harryr


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;
}
like image 43
npace Avatar answered Oct 14 '22 05:10

npace