Difference Between Getstring() and Getresources.Getstring()

Difference between getString() and getResources.getString()

They are the same as Activity.getString(int) does exactly that:

 public final String getString(int resId) {
return getResources().getString(resId);
}

Difference between getting resource via getResource() vs direct way

The only difference is that
resources.getString(R.string.ticketDetailsContactFragment_cannot_send_email)

and

getString(R.string.ticketDetailsContactFragment_cannot_send_email)

will return a String

instead
R.string.ticketDetailsContactFragment_cannot_send_email return its resId (int value)

When to use getString()

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():

/**
* Return the string value associated with a particular resource ID. It
* will be stripped of any styled text information.
* {@more}
*
* @param id The desired resource identifier, as generated by the aapt
* tool. This integer encodes the package, type, and resource
* entry. The value 0 is an invalid identifier.
*
* @throws NotFoundException Throws NotFoundException if the given ID does not exist.
*
* @return String The string data associated with the resource,
* stripped of styled text information.
*/
public String getString(int id) throws NotFoundException {
CharSequence res = getText(id);
if (res != null) {
return res.toString();
}
throw new NotFoundException("String resource ID #0x"
+ Integer.toHexString(id));
}

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():

Return a localized string from the application's package's default
string table.

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 :)

Difference in retrieving String and String Array resources?

How come I have to do Resources res = getResources(); for a String
Array, and not for a String in an XML file?

getString() is a method of your Context object (mostly an Activity but could also be a Service). The code for that method is:

public final String getString(int resId) {
return getResources().getString(resId);
}

Meaning getString() is just a convenience method that the Context class offers. In the end both calls do the same, namely retrieve a resource through the Resource object.

Would String[] planets = getStringArray(R.array.planets_array); not
work?

No because Context doesn't have a convenience method to retrieve String[].

Do resources have more methods, namely for more complex cases like
String Arrays?

Yes. See http://developer.android.com/reference/android/content/res/Resources.html.
I leave if up to you to decide whether they are more complex than getStringArray.

is getString so simple it is fine to not need it under a resource?

Resource does have a getString(int) method: http://developer.android.com/reference/android/content/res/Resources.html#getString(int)

Where could I find a list separating what requires me to do Resources
res = getResources(); versus what doesn't require that?

There's no such list. The JavaDoc for Context will tell you what convenience method you got:
http://developer.android.com/reference/android/content/Context.html

Lastly, does getResources get me every single resource in my Android
project regardless of what XML file it may be in?

Only if it's in a resource xml file. Layouts or Drawables can't contain String resources.

Is calling getResources().getString(string_id, params) inside loop degrades performance

The best way to answer a question like this is to try it out and measure the results. I made these strings:

<string name="plain">Hello world</string>
<string name="variable">Hello %1$s</string>

And then I made an app that loaded each of them once, and then each of them a thousand times, and measured the number of nanoseconds that took. I ran it on a pretty old tablet running a pretty old version of Android, and got these results:

getString(R.string.plain);
getString(R.string.variable, "StackOverflow");
I/System.out(31427): Loading one plain string took 91,552 nanos
I/System.out(31427): Loading one variable string took 183,106 nanos
I/System.out(31427): Loading a thousand plain strings took 38,055,421 nanos
I/System.out(31427): Loading a thousand plain strings took 67,352,294 nanos

So, it takes 0.18 milliseconds to load a string with format arguments a single time, and 67.35 milliseconds to do the exact same thing a thousand times. My conclusion is that loading the same resource repeatedly has some optimization, but not an incredible amount (it took about one third as long as we'd expect with no optimization).

I also measured the same test using String.format("Hello %s", "StackOverflow"), and got these results:

String.format("Hello %s", "StackOverflow");
I/System.out(31849): Formatting one variable string took 152,588 nanos
I/System.out(31849): Formatting a thousand variable strings took 22,613,526 nanos

So doing the formatting directly in java is marginally faster for a single attempt, but significantly faster when repeated.

Finally, a test that bridges the gap. I use getString() without format arguments, and then String.format() to do the formatting. This means I only access the resources framework a single time, but still get the benefits of internationalization etc. Here are my results

String template = getString(R.string.variable);
String.format(template, "StackOverflow");
I/System.out(32094): Formatting one variable string took 213,623 nanos
I/System.out(32094): Formatting a thousand variable strings took 28,015,135 nanos

Here, a single invocation is the worst performer of them all. This makes sense; we're manually doing all the work we were getting "for free" before. But doing it a thousand times is still a significant win over loading from resources every time.


All in all, the question still comes down to what you're doing, how often you're doing it, and what kind of performance you need. Consider that Android draws a frame to the screen approximately every 16 milliseconds... loading a thousand variable strings from resources would cause you to skip 3-4 frames. But if you're only loading a hundred strings, then you wouldn't skip any.

Different ways to get string

Hi The Android resource system keeps track of all non-code assets associated with an application. You can use this class to access your application's resources. You can generally acquire the Resources instance associated with your application with getResources().

practically there is no difference in getString(R.string.your_string) and getResources().getString(R.string.my_string); but I will suggest you to always use getResources().getString(R.string.my_string); for calling the resources.

R.string.my_string; will return the id(int) of the my_string. So this work like this getResources() is parent class contain all the resources of application by getString() you are informing the processor that your resource type is string and by R.string.my_string you give the id of your string.
Hope you understand.

Difference between R.string.xxx and getString(R.string.xxx)?

R.string.some_string

is a public final static int that is a fixed ID to a specific String in your R.java file. This is generated automatically.

getString(R.string.some_string)

returns the String referenced by the above by reading the R.java file.

It depends on the implementation of

setPositiveButton(String)

and

setPositiveButton(int)

what difference internally is made, like with error checks.

What is the difference between getString() and getText()?

From the doc,

For Resources.getString():

Return the string value associated with a particular resource ID. It
will be stripped of any styled text information.

For Resources.getText():

Return the string value associated with a particular resource ID. The
returned object will be a String if this is a plain string; it will be
some other type of CharSequence if it is styled.

[Note that Context.getText() and Context.getString() internally calls the methods from Resources.]

The doc says that getText() retains the styling while the getString() not. But you can use either one to get the string resource with HTML tags from strings.xml, but the way is different.

Using Resources.getText():

strings.xml:

<string name="styled_text">Hello, <b>World</b>!</string>

You can just call getText() (note that it returns a CharSequence not a String, so it has the styling properties) and set the text to TextView. No need for Html.fromHtml().

mTextView.setText(getText(R.string.styled_text));

But the doc says only a limited HTML tags, such as <b>, <i>, <u> are supported by this method. The source code seems to suggest it supports more than that: <b>, <i>, <u>, <big>, <small>, <sup>, <sub>, <strike>, <li>, <marquee>, <a>, <font> and <annotation>

Using Resources.getString():

strings.xml:

<string name="styled_text"><![CDATA[Hello, <b>World</b>!]></string>

You have to surround your string in a CDATA block and calling getString will return the string with HTML tags. Here you have to use Html.fromHtml().

mTextView.setText(Html.fromHtml( getString(R.string.styled_text)));

Html.fromHtml() is deprecated in favor of a new method with flags parameter. So use it like this:

HtmlCompat.fromHtml(getString(R.string.styled_text))

Implementation of the util method HtmlCompat.fromHtml:

public class HtmlCompat {

public static CharSequence fromHtml(String source) {

if(Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {

//noinspection deprecation
return Html.fromHtml(source);

} else {

return Html.fromHtml(source, Html.FROM_HTML_MODE_COMPACT);
}
}

}

What is the difference in accessing an external string from a resource using a different method?

TL;DR

It doesn't matter whether you use R.string.hello or getResources().getString(R.string.hello).
Both will point the same thing.

So, yes, for your localization, then it will point to the right stuff.
It's been taken care of.

Some trivial stuff:

R.string.hello is actually an integer.
And most methods, that are used by passing R.string.hello (or other resources) as its argument, basically have the function to translate to corresponding string of the number.

Let's take TextView as an example.

It has two methods for setText.

First:

public final void setText(CharSequence text)

Second:

public final void setText(int resid)

So, when you call using getResources().getString():

myTextView.setText(getResources().getString(R.string.hello);

Then the first method is called.

And when you call using R.string.hello directly, then the second method is called.

If you take a look closer to the source, the second method's content (calling using R.string.hello directly) is actually calling the first method.

https://github.com/android/platform_frameworks_base/blob/master/core/java/android/widget/TextView.java#L4133

Both are provided for our convenience, so that we can use either direct resource R.string.hello or using getResources().getString(R.string.hello).



Related Topics



Leave a reply



Submit