Avoid looking up all locales for system language

This commit is contained in:
serso 2016-01-25 19:56:26 +01:00
parent 251bb10965
commit 362ec885fe

View File

@ -21,8 +21,8 @@ public final class Languages implements SharedPreferences.OnSharedPreferenceChan
public static final String SYSTEM_LANGUAGE_CODE = "00"; public static final String SYSTEM_LANGUAGE_CODE = "00";
@Nonnull @Nonnull
public static final Language SYSTEM_LANGUAGE = new Language(SYSTEM_LANGUAGE_CODE, Locale.getDefault()); public static final Language SYSTEM_LANGUAGE = new Language(SYSTEM_LANGUAGE_CODE, Locale.getDefault());
@Nonnull @Nullable
private static final Locale[] locales = Locale.getAvailableLocales(); private static Locale[] locales;
@Nonnull @Nonnull
private final List<Language> list = new ArrayList<>(); private final List<Language> list = new ArrayList<>();
@Nonnull @Nonnull
@ -43,7 +43,7 @@ public final class Languages implements SharedPreferences.OnSharedPreferenceChan
@Nullable @Nullable
private static Locale findLocaleById(@Nonnull String id) { private static Locale findLocaleById(@Nonnull String id) {
for (Locale locale : locales) { for (Locale locale : getLocales()) {
if (TextUtils.equals(locale.toString(), id)) { if (TextUtils.equals(locale.toString(), id)) {
return locale; return locale;
} }
@ -57,7 +57,7 @@ public final class Languages implements SharedPreferences.OnSharedPreferenceChan
language = id; language = id;
} }
for (Locale locale : locales) { for (Locale locale : getLocales()) {
if (TextUtils.equals(locale.getLanguage(), language)) { if (TextUtils.equals(locale.getLanguage(), language)) {
return locale; return locale;
} }
@ -67,6 +67,14 @@ public final class Languages implements SharedPreferences.OnSharedPreferenceChan
return null; return null;
} }
@Nonnull
public static Locale[] getLocales() {
if (locales == null) {
locales = Locale.getAvailableLocales();
}
return locales;
}
/** /**
* This method should be called only when default values have been set to application's preferences * This method should be called only when default values have been set to application's preferences
*/ */
@ -128,6 +136,10 @@ public final class Languages implements SharedPreferences.OnSharedPreferenceChan
@Nonnull @Nonnull
public Language get(@Nonnull String code) { public Language get(@Nonnull String code) {
if (TextUtils.equals(SYSTEM_LANGUAGE.code, code)) {
// quick check to avoid list loading
return SYSTEM_LANGUAGE;
}
Language language = findLanguageByCode(code); Language language = findLanguageByCode(code);
if (language != null) { if (language != null) {
return language; return language;