Search code examples
androidstringclassidentifier

Why .getIdentifier() retreive a number from class?


When I try to get a string from an activity, "getIdentifier" works fine:

Toast.makeText(this, getResources().getIdentifier("frase", "string", getPackageName()), Toast.LENGTH_SHORT).show();

But when try it from non activity class, it retreive a number (e.g.: 2131099793):

getContext().getResources().getIdentifier("frase" , "string", getContext().getPackageName();

Why does this happen?


Solution

  • getIdentifier() returns an int, as you can see in the JavaDocs. That int is the identifier of the resource. In your case, it is the same int that R.string.frase is.

    In your first code snippet, you pass that resource identifier to Toast.makeText(). makeText() assumes that if you pass it an int, that the int is a string resource identifier, so it looks up the string resource and uses it.

    In your second code snippet, you are just using the int. Use getString() to convert an int resource identifier into the corresponding string for your current configuration.