0

In order to format a string, I always use String.format(getString(R.string.something),arg1)

However I saw on the documentation getString(string, args) could do the same.

Therefore, I wonder why everyone use String.format if getString can do the same

Thank you

4
  • The answer is Yes. See the most upvoted ansewr here. stackoverflow.com/questions/12627457/… Commented Nov 11, 2016 at 11:32
  • @Doomsknight, the question is Why?. The answer can't be Yes Commented Nov 11, 2016 at 11:43
  • 1
    @VladMatvienko Wrong wording sorry. By that i mean they are the same, except one is more direct. Not everyone knows of better ways, and as per the linked answer, you can see that the accepted answer denotes one method, and the most upvoted answer, denotes the second. So it is more of what people come across to what is used. I don't always program optimally either. Some APIs are also introduced at a later date, after certain ways of coding are already documented. Commented Nov 11, 2016 at 11:50
  • 1
    Also noting from the documentation, it shows example usage of the first method, not the second. So people using it as reference follow the first usage. developer.android.com/guide/topics/resources/… Commented Nov 11, 2016 at 11:54

1 Answer 1

2

You are mistaken, there is no method Resources.getString(string, args...) or Context.getString(string, args...). There is Resources.getString(int, args...) that takes an int and objects.

When formatting a string you would use String.format(string, args...). But in Android your string resources are probably in the res folder so you have a convinience method for getting the string from the resources and formatting it with String.format. It does the same thing as you did (taken from Android source):

@NonNull
public String getString(@StringRes int id, Object... formatArgs) throws NotFoundException {
    final String raw = getString(id);
    return String.format(mResourcesImpl.getConfiguration().getLocales().get(0), raw,
            formatArgs);
}

You would use it like:

getString(R.string.something, arg1)

and save yourself some typing.

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

2 Comments

Sorry, yes, you are right. I misunderstood your answer first time because it is written in a quite complicated language.
I assume his question actually meant Resources.getString(int, args...) And that its more aimed at why they use one method over the other

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.