Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - What's the difference between Locale.toString() and Locale.toLanguageTag()?

Tags:

I have a piece of code where I'm trying to change the language in my app, using a Spinner View Component. While working with this, I've come to realize that I'm probably not using the most smooth method, but more intrestingly, I've noticed that two strings that LOOK the same are not equal when compared. Why is it like this, and how should I do if I want to "check" if the language is a certain one?

if (myLocale.toLanguageTag()=="sv") 
{
    //Changing language from Swedish to English
}
else 
{
    Toast.makeText(parent.getContext(),
      myLocale.toString(), Toast.LENGTH_SHORT).show();
   //Here, the toast will tell me what myLocale.toString is "sv", 
   //and so is myLocale.toLanguageTag(). Yet they are not equal...
}
like image 634
Zerato Avatar asked Oct 09 '17 16:10

Zerato


1 Answers

As stated in the documentation:

Locale.toString() returns a string representation of this Locale object, consisting of language, country, variant, script, and extensions, whatever is available, as below:

language + "_" + country + "_" + (variant + "_#" | "#") + script + "-" + extensions

Language is always lower case, country is always upper case, script is always title case, and extensions are always lower case.
for example en_US, en

Whereas Locale.toLanguageTag() returns you the same stuff (language, country, and variant), but as a tag. Here Tag means some code given for language, country and variant defined by some IETF's BCP 47 standard (BCP = 'Best Current Practice').
for example en-US
The only difference I can see is the _ and - or perhaps some language/country codes too.

In nutshell, both of them return String; one returns a normal string representation of the Locale whereas the later returns a string as a well-formed IETF BCP 47 language tag representing the locale.

The documentation also suggests using toString only in debugging mode:

This behavior is designed to support debugging and to be compatible with previous uses of toString that expected language, country, and variant fields only. To represent a Locale as a String for interchange purposes, use toLanguageTag().

Hope it helps.

like image 123
Niraj Niroula Avatar answered Sep 29 '22 23:09

Niraj Niroula