Klaasvaak
Klaasvaak

Reputation: 5644

getIdentifier() always returns 0

I am trying to get the ID of a string with value "Hello" from strings.xml doing to following:

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

It returns 0. Why is this returning 0?

Upvotes: 2

Views: 3902

Answers (2)

Yan
Yan

Reputation: 1726

In case package name in Manifest differs you won't get an identifier because your package name is incorrect, in order to get correct package name for resources dynamically you should use:

String rPackageName = mContext.getResources().getResourcePackageName(R.some.wellKnownResource);

'rPackageName' is a package name that you should pass to the function

getIdentifier(String name, String defType, String defPackage)

Upvotes: 1

andr
andr

Reputation: 16054

Because you're passing the string value, while you should pass the resource name of the string.

Look at the method signature: getIdentifier(String name, String defType, String defPackage).

When the resource is not found, 0 is returned which is consistent with what you're experiencing.

Edit:

  1. Use of getIdentifier() is discouraged - to quote the reference:

    Note: use of this function is discouraged. It is much more efficient to retrieve resources by identifier than by name.

  2. I know no direct way of getting the ID of a string based on value of the string in question. However I've seen two workarounds/hacks:

    1. Name all strings for which you want the lookup to be performed like this: stringN where N is for example 0-based integer incremented for each of the strings. You end up with ugly names like string0, string1, etc. Then you do the lookup yourself - you iterate over N, create string ID: stringN, get its value and check for a match. This is ugly in my opinion.

    2. Use Typed Array resource and put all your strings there. It's basically the same as method 1, but avoids creation of nasty, polluting resource names.

Upvotes: 5

Related Questions