Home » Android » android – Lollipop Set Default local does not work

android – Lollipop Set Default local does not work

Posted by: admin June 15, 2020 Leave a comment

Questions:

I have this method running on most of android API versions to set app using language (strings etc)

protected void setDefaultLocale(Context context, Locale locale) {
    Locale.setDefault(locale);
    Configuration appConfig = new Configuration();
    appConfig.locale = locale;
    context.getResources()
            .updateConfiguration(appConfig, context.getResources().getDisplayMetrics());
    System.out.println("trad" + locale.getLanguage());
}

@Override
protected void onCreate(Bundle savedInstanceState) {

    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    String language = sharedPref.getString("pref_language", "he_IL");
    if (!language.equals("")) 
        setDefaultLocale(this, new Locale(language));

    super.onCreate(savedInstanceState);


}

When using this on lollipop running device nothing change.

Anyone know how to solve this?

How to&Answers:

Responses above work but just for the language, when you want to use for example:

NumberFormat numberFormat = NumberFormat.getCurrencyInstance(Locale.getDefault());

modifying the default locale before, doesn’t work anymore as it did in previous android versions.

Has changed the way the locale has been initialized (I don’t know why, I took a look in the API and says nothing).

So change the way you initialize your locale, from this:

Locale locale = Locale("en_US")

to this:

Locale locale = new Locale("en", "US");

and it works like a charm 🙂

Hope this helps someone in the future.

Cheers

Answer:

I noticed a similar behavior in lollipop, but not in previous versions of the API.

In my case the problem was because I was setting, like you, the language code and the country code, but my resource folders were language specific, only “values-fr” and “values-es”, etc.

If you set this line

String language = sharedPref.getString("pref_language", "he_IL");

to

String language = sharedPref.getString("pref_language", "he");

does it work as expected?

I only needed the language code, so setting just that solved it for me.

Answer:

Finally found the answer.

The answer was using “iw” instead of he_il.

String language = sharedPref.getString(“pref_language”, “iw”);