-2

I have a resources file that looks like:

<string name="snapshot_type_1">Deletion</string>
<string name="snapshot_type_2">Insertion</string>
<string name="snapshot_type_3">Edition</string>

What I want is to be able to restrieve the string based on pased on the number that identifies the type, this way:

"snapshot_type_" + someVariableValue

Of course, the approach resources.getString(R.string.snapshot_type_1) is not working because it receives an integer.

Thank you!

forpas
  • 160,666
  • 10
  • 38
  • 76
Mr.Eddart
  • 10,050
  • 13
  • 49
  • 77

1 Answers1

3

You get the id of the string resource like this:

int id = getResources().getIdentifier("snapshot_type_" + someVariableValue, "string", getPackageName());

and then the resource value:

String value = getResources().getString(id);

Maybe you need to supply a valid Context to getResources() and getPackageName() if your code is not in an activity class.
But in cases like this I think it would be better to use a string array:

<string-array name="snapshot_types">
    <item>Deletion</item>
    <item>Insertion</item>
    <item>Edition</item>
</string-array>

and get it like this:

String[] snapshotTypes = getResources().getStringArray(R.array.snapshot_types);
forpas
  • 160,666
  • 10
  • 38
  • 76