Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

toUpperCaseLocale() vs toUpperCase() - Now targeting Android 4.2

Tags:

android

Since I targeted a newer SDK version of Android, I have been getting a warning on this line of code:

return getString(R.string.usertab1).toUpperCase()

When I hover over it, it says:

Implicitly using the default locale is a common source of bugs: Use toUpperCase(Locale) instead.

Does anyone know how to remove this error? And why is it now a preferred way to use this method?

I get this is the answer, to use toUpperCase(Locale) but having trouble implementing it. Where does the Locale object come from?

like image 299
TheLettuceMaster Avatar asked Nov 23 '12 21:11

TheLettuceMaster


1 Answers

You could explicitly use the default locale:

return getString(R.string.usertab1).toUpperCase(Locale.getDefault());

Basically, you don't want to implicitly allow the device to use the default, because this can mean you simply ignored the fact that it could be an issue. For machine-readable content, you may want to specify a specific locale (such as Locale.ENGLISH) to ensure you always get the reusability you want out of the data. For showing the user, explicitly specifying the default locale should be fine.

For a more complete read:

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.

-- Locale developer documentation

like image 77
Cat Avatar answered Nov 11 '22 14:11

Cat