1

Is there a way to get a specific resource from my "strings.xml" based on runtime value?

To explain more, I have a list of values, i.e. taxi fares for each location - i.e. different for Bangalore, Chennai, etc.

my Strings.xml looks something like this:

<string-array name="Bengaluru">
    <item>Min Fare | 100</item>
    <item>Per KM Fare |10</item>
    </string-array>

In my MainActivity, I'm using code like this:

String currentCity = <Getting the city via phone location method>
if(currentCity.equals("Bengaluru")) {

    // My method to extract values from the string
    myCustomParser(getResources().getStringArray(R.array.Bengaluru));
}

(I probably will replace if with Switch-Case, but isn't there a way to rewrite the above as:

  // My method to extract values from the string
    myCustomParser(getResources().getStringArray(R.array.currentCity));

i.e. dynamic replacement of the value I want to pull out from the resource file?

Thanks

zooter
  • 2,128
  • 1
  • 13
  • 23
  • You should not use `==` for String comparison. Use `equals()` instead. – user2004685 Apr 03 '16 at 18:20
  • This [answer](http://stackoverflow.com/a/3476470/1435985) should get you on the right track on how to look up a resources id by its name if you wanted to go that route. – George Mulligan Apr 03 '16 at 18:22
  • Possible duplicate of [How to get a resource id with a known resource name?](http://stackoverflow.com/questions/3476430/how-to-get-a-resource-id-with-a-known-resource-name) – George Mulligan Apr 03 '16 at 18:27

1 Answers1

2

Yes, you can use Resources.getIdentifier(String name, String defType, String defPackage). Example of usage:

myCustomParser(getResources().getStringArray(
    getResources().getIdentifier("Bengaluru", "array", getPackageName()));
Eduard B.
  • 6,735
  • 4
  • 27
  • 38