Search code examples
javaandroidandroid-resources

Android Getting resource string based on runtime value


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


Solution

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

    myCustomParser(getResources().getStringArray(
        getResources().getIdentifier("Bengaluru", "array", getPackageName()));