Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any difference in using Context.getText and Context.getResources.getText?

So I've noticed that there seem to be two ways to get the same data, and I'm not sure if there are guidelines to when you should use either (other than, bypassing the getResources could be memory saving if you don't actually want to use the object more than once). But other than that I would like to know if there are guidelines or reasons to use

Context.getText(id) vs Context.getResources.getText(id)

Can anyone help?

like image 675
Hayley Avatar asked Feb 22 '12 17:02

Hayley


People also ask

What is the use of getResources() in android?

The documentation for getResources() says that it will [r]eturn a Resources instance for your application's package. In code examples I've seen this used to access the resources in res , but it seems like you can just access them directly. For example to retrieve my_string from res/values/strings.

What is context Mode_private?

Context. MODE_PRIVATE is an int constant with value zero; refer to the javadoc linked above for the details. The former is more readable though, and that makes it preferable from a code style perspective.

What does context mean in Android?

Definition. it's the context of current state of the application/object. It lets newly-created objects understand what has been going on. Typically, you call it to get information regarding another part of your program (activity and package/application).

How do I find application context?

You can go for getApplicationContext() if you wanna get context of whole application. If you want to get context of current class you can use getBaseContext() instead.


2 Answers

There is no difference. The source for getText(id) is:

/**
 * Return a localized, styled CharSequence from the application's package's
 * default string table.
 *
 * @param resId Resource id for the CharSequence text
 */
public final CharSequence getText(int resId) {
    return getResources().getText(resId);
}

You can see for yourself at Context.java on netmite which has a version of the Android source.

like image 139
Justin Breitfeller Avatar answered Nov 11 '22 07:11

Justin Breitfeller


If you just want the text, you can use the Context.getText(id) method. Getting the resource with Context.getResoures() allows you to test other properties of it.

like image 35
Furbeenator Avatar answered Nov 11 '22 08:11

Furbeenator