0

I'm getting started with an Android project and I encountered this issue.

I'm trying to create a switch where the cases are string got with

case getString(R.string.myString): ...

but I'm getting a

Constant expression required

error.

I didn't want to create a cascade of if statements (this wouldn't require constant values, but it's less readable) so, is there a way to have a switch with strings taken from the strings.xml file?

Thank you for your help!

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Luca De Nardi
  • 2,280
  • 16
  • 35
  • 1
    You cannot use switch case for this. Better use if else – hasan_shaikh Jul 16 '18 at 13:32
  • https://stackoverflow.com/questions/29541914/using-string-from-resource-xml-in-switch – faran.javed Jul 16 '18 at 13:33
  • Wow, I was wondering if I was missing something, but it's indeed not possible then. Also thanks @faran.javed for the link, I searched with many search terms but still couldn't find that question. – Luca De Nardi Jul 16 '18 at 13:35
  • You can't do that, because `getString()` needs context and it finds its value after creating the activity or current context while `case` needs constant. – salmanseifian Jul 16 '18 at 13:45

2 Answers2

0

It simply mean switch case allow only constant values.

Here is a good example to show why switch only allow constants only.

You can use if-else statement for this purpose.

Khemraj Sharma
  • 57,232
  • 27
  • 203
  • 212
0

Instead of getting String from resource (string.xml) file. Define that String in Constant.java class as below:-

public static final String DOWNLOAD_DOCUMENTS = "com.android.providers.downloads.documents";

and use that Constant field in switch block :-

switch(input) {
   case DOWNLOAD_DOCUMENTS :
    // your logic 
   break;
}