According to the Java reference, Locale.getLanguage()
is supposed to return the 2-letters lowercase ISO code of the language (e.g. en
), while getDisplayLanguage()
is the method for obtaining the readable name (e.g. English
).
So how comes that the following code in Android:
Locale.getDefault().getLanguage()
returns English
or Español
instead of en
and es
????
I'm completely puzzled...
As described in Locale reference the best way to get language is: Locale.getDefault().getLanguage() this method returns string with language id according to ISO 639-1 standart.
Locale getDefault() method in JavaThis method returns default Locale set by the Java Virtual Machine. This is static method so it can be called without creating object of the class Locale. Syntax: public static Locale getDefault() Return Value: The method returns default Locale set by the Java Virtual Machine.
The default Locale is constructed statically at runtime for your application process from the system property settings, so it will represent the Locale selected on that device when the application was launched.
Configuration config = new Configuration(); config. locale = selectedLocale; // set accordingly // eg. if Hindi then selectedLocale = new Locale("hi"); Locale. setDefault(selectedLocale); // has no effect Resources res = getApplicationContext().
I've figured it out. This happened because I had previously called Locale.setDefault() and passed it a Locale which in turn I had created by erroneously passing it the whole language name (I took the language from a preference setting and I mistakenly picked the label of the entry instead of the value).
That is, I did:
String lang= //... here I assigned "English" while I thought
// I was assigning it "en"
Locale locale=new Locale(lang);
Locale.setDefault(locale); // (*)
// and later
Locale.getLocale().getLanguage(); //returns "english"
So when I queried for the default locale, it actually was the locale I had created whose language code I had erroneously set to "english".
There are a couple of funny things, though:
Use
getResources().getConfiguration().locale.getLanguage()
and it will work just fine even though I would consider your observed behaviour a bug worth reporting..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With