So I am trying to make an app in which you can change the language (in a preference activity) to system default or a specific language. Whenever you change the language the app is restarted and the new locale is selected. When the first activity starts, it saves the Locale which has to be used into a static variable in an Utils class. In every activity onCreate method I load that locale.
Now, for clarification, here's the Locale part of the Utils class:
private static Locale locale = null;
public static boolean isLocaleNull() {
return locale == null;
}
public static void setLocale(Locale locale) {
Utils.locale = locale;
}
public static void loadLocale(Context baseContext) {
if (locale == null) return;
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
baseContext.getResources().updateConfiguration(config, baseContext.getResources().getDisplayMetrics());
}
Here's my onCreate on my first activity (only locale part):
if (!Utils.isLocaleNull()) {
String locale = PreferenceManager.getDefaultSharedPreferences(getBaseContext())
.getString(getResources().getString(R.string.prefsKeyLanguage), "default");
if (locale != null && !locale.equals("default"))
Utils.setLocale(new Locale(locale));
}
And here's how I load the locale in all activities:
Utils.loadLocale(getBaseContext());
Finally, in the loadLocale we have if (locale == null) return;
and in the locale loader we have if (... && !locale.equals("default"))
which means the locale will be null if System Default is selected which means the locale won't be change if System Default is selected.
Everything's perfect! I mean, it works as expected. But can it fail in some cases? Is it a good idea? I know that holding static references to instances is a bad idea in some cases. Is this one of those some cases? If yes, what should I do?
Thanks!