I am wondering about the getString().
I can see that doing getString(R.string.some_text)
works. Also getResources().getString(R.string.connection_error)
works.
So my question is why should we use the getString or when?
Thanks!
When to use getString()
12.9k views Asked by roiberg AtThere are 5 answers
If you use it for TextView there are two methods setText() in it. One takes (CharSequence string) and another takes (int resId). That's why your both variants work.
Generally I would recommend to define all strings in strings.xml files and get them via getResources().getString(int resId) in the code. Having that approach you'll be able to easily localize your app. You can read more about app resources here
Very Basic difference.
R.string.some_text = return ID integer, identifying string resource in your space
getResources().getString(R.string.connection_error) = Will return you actualy string associated with ID `R.string.connection_error`
They both can be made use in Android system, where many of widgets can take directly id or value of a resource. Practically there is no difference in value returned only difference is is the Term Context
, from you activity context is available to you hence calling getString
directly routes to resources for this context, while from classes where context is not available say from a Adapter, you will need to first access the Context, then the resource associated with the context and at the end the String so you write getContext().getResources().getString(R.string.connection_error)
I hope it clears your confusion.
The methods are same. Logically, there's not a difference. you can assume, it does exactly:
public final String getString(int resId) {
return getResources().getString(resId);
}
The only difference I know is that getResources() may be required to fetch other apps resources as object. getString() will access your own resources.
One good reason is about formating & styling like :(http://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling)
The question is easy to misinterpret.
If you are in a valid context (like an Activity), there is no difference, because the context has a reference to the resources, so it can resolve a
getString(int);
directly, which returns a String.Adding more information for your peace of mind.
If you can use getString directly, go ahead and do it. Now sometimes you might need to use getResources() because it contains a lot of helper methods.
This is the Android source code for
getResources.getString()
:Neat huh? :)
The truth is that the Resources object does a lot more than just "get strings", you can take a look here.
Now compare with the Activity version of getString():
So in summary, other than the fact that the Resources object will
be stripped of any styled text information.
and that the Resources object can do a lot more, the end result is the same. The Activity version is a convenient shortcut :)