1

Let's imagine we had this text inside values/strings.xml

<string name="some_text">HELLO WORLD</string>

I can call this string from anywhere inside my project like so:

String s = String.valueOf(R.string.some_text);

Today I learnt this other way to do exactly the same job:

String s = getResources().getString(R.string.some_text);

Does anyone know if there is any advantage in using the second way? The first one seems shorter and easier to remember.

Thanks

2
  • That is the first that I have seen of String.valueOf( ) working. Intriguing if true as then I wouldn't need to call getResources( ) from odd locations that might not have immediate access to them. Commented Feb 24, 2015 at 19:53
  • 1
    I'm pretty sure String.valueOf(R.string.some_text) will turn whatever the int identifier value is for that string into a String representation of that number. Not what you want. Also, if you are calling getString from an Activity or a Fragment, you don't have to call getResources() first as there is a convenience getString method you can use. Commented Feb 24, 2015 at 20:08

2 Answers 2

1

Try to compare or output the value of s for the two methods. They are not the same :) String.valueOf(R.string.some_text) returns string representation of a resource id integer. getResources().getString(R.string.some_text); probably does what you wanted.

Correct way is getResources().getString(R.string.some_text); and there are other convenience methods as mentioned by @danny117 but they are dependant of the location of the specific code

Sign up to request clarification or add additional context in comments.

Comments

1

Look at the class your working with. For example the fragment class has a built in getString() function so you can just call it.

getString(R.string.me)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.