Issue
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?
Solution
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:
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.
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:
Name all strings for which you want the lookup to be performed like this:
stringN
whereN
is for example 0-based integer incremented for each of the strings. You end up with ugly names likestring0
,string1
, etc. Then you do the lookup yourself - you iterate overN
, create string ID:stringN
, get its value and check for a match. This is ugly in my opinion.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.
Answered By - andr
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.