-1

I am looking for a guide as to how i can implement switch that would get values from a string array. Basically, i have a spinner with all the items as stated in my array, so i want to implement a switch so that whenever i click on an item, it will trigger an event, for example, going to another activity.

<string-array name="location1">

    <item>string a</item>
    <item>string a</item>
    <item>string b</item>
    <item>string c</item>
    <item>string d</item>

</string-array>

So, if i have a string array like this, how should I implement my switch statement?

AYS
  • 17
  • 8
  • 2
    You cannot use switch on strings before JDK 7. I am not sure I understand your question. Can you tell us more about what you want to do? (see http://stackoverflow.com/questions/338206/switch-statement-with-strings-in-java ) – Romain Guidoux Oct 03 '12 at 09:34
  • @Romain Guidoux Oh :/ well basically i have a spinner with all the items as stated in my array, so i want to implement a switch so that whenever i click on an item, it will trigger an event, for example, going to another activity. – AYS Oct 03 '12 at 11:23

2 Answers2

2

If array is:

<string-array name="cars_array">
    <item>Audi</item>
    <item>Ferrari</item>
</string-array>

You can access them like this:

Resources res = getResources();
String[] cars = res.getStringArray(R.array.cars_array);

then you can access them individually as cars[0], cars[1] etc

If you want to access the same string resource as part of an array and individually as well, then you can do this:

<string name="audi">Audi</string>
<string name="ferrari">Ferrari</string>

<string-array name="cars_array">
    <item>@string/audi</item>
    <item>@string/ferrari</item>
</string-array>

Then you can simply say "@string/audi" to get it individually as well as you can use the array name "@string/cars" to use the string array as a whole.

Anup Cowkur
  • 20,443
  • 6
  • 51
  • 84
-1

I think this resource on Android Developers site might help you : String Resources

It will get you something like that :

Resources res = getResources();
String[] strArray = res.getStringArray(R.array.location1);
Rémi F
  • 1,327
  • 12
  • 25