Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android get system locale different approaches

So, I found out that there are two approaches to get system's locale in Android:

Locale.getDefault()

And

getResources().getConfiguration().locale

Basically question is - can output differ for these two? Or are they always the same and I can use the first one, since it does not require Context object?

like image 385
Heisenberg Avatar asked Oct 30 '22 19:10

Heisenberg


2 Answers

Quoted from this page:

Be wary of the default locale

Note that there are many convenience methods that automatically use the default locale, but using them may lead to subtle bugs.

The default locale is appropriate for tasks that involve presenting data to the user. In this case, you want to use the user's date/time formats, number formats, rules for conversion to lowercase, and so on. In this case, it's safe to use the convenience methods.

The default locale is not appropriate for machine-readable output. The best choice there is usually Locale.US – this locale is guaranteed to be available on all devices, and the fact that it has no surprising special cases and is frequently used (especially for computer-computer communication) means that it tends to be the most efficient choice too.

A common mistake is to implicitly use the default locale when producing output meant to be machine-readable. This tends to work on the developer's test devices (especially because so many developers use en_US), but fails when run on a device whose user is in a more complex locale.

For example, if you're formatting integers some locales will use non-ASCII decimal digits. As another example, if you're formatting floating-point numbers some locales will use ',' as the decimal point and '.' for digit grouping. That's correct for human-readable output, but likely to cause problems if presented to another computer (parseDouble(String) can't parse such a number, for example). You should also be wary of the toLowerCase() and toUpperCase() overloads that don't take a Locale: in Turkey, for example, the characters 'i' and 'I' won't be converted to 'I' and 'i'. This is the correct behavior for Turkish text (such as user input), but inappropriate for, say, HTTP headers.

like image 137
JoeyJubb Avatar answered Nov 11 '22 12:11

JoeyJubb


Locale current = getResources().getConfiguration().locale;

You may find that this value is updated more quickly after a settings change if that is necessary for your application.

Which is not in your another method

like image 23
Androider Avatar answered Nov 11 '22 10:11

Androider