aboutsummaryrefslogtreecommitdiff
path: root/libs/utils/WordPressUtils/src/main/java/org/wordpress/android/util/LanguageUtils.java
blob: 515b044b331a96e4195bc7f01a23bc9b5d1c4233 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package org.wordpress.android.util;

import android.content.Context;

import java.util.Locale;

/**
 * Methods for dealing with i18n messages
 */
public class LanguageUtils {

    public static Locale getCurrentDeviceLanguage(Context context) {
        //better use getConfiguration as it has the latest locale configuration change.
        //Otherwise Locale.getDefault().getLanguage() gets
        //the config upon application launch.
        Locale deviceLocale = context != null ? context.getResources().getConfiguration().locale : Locale.getDefault();
        return deviceLocale;
    }

    public static String getCurrentDeviceLanguageCode(Context context) {
        String deviceLanguageCode = getCurrentDeviceLanguage(context).toString();
        return deviceLanguageCode;
    }

    public static String getPatchedCurrentDeviceLanguage(Context context) {
        return patchDeviceLanguageCode(getCurrentDeviceLanguageCode(context));
    }

    /**
     * Patches a deviceLanguageCode if any of deprecated values iw, id, or yi
     */
    public static String patchDeviceLanguageCode(String deviceLanguageCode){
        String patchedCode = deviceLanguageCode;
        /*
         <p>Note that Java uses several deprecated two-letter codes. The Hebrew ("he") language
         * code is rewritten as "iw", Indonesian ("id") as "in", and Yiddish ("yi") as "ji". This
         * rewriting happens even if you construct your own {@code Locale} object, not just for
         * instances returned by the various lookup methods.
         */
        if (deviceLanguageCode != null) {
            if (deviceLanguageCode.startsWith("iw"))
                patchedCode = deviceLanguageCode.replace("iw", "he");
            else if (deviceLanguageCode.startsWith("in"))
                patchedCode = deviceLanguageCode.replace("in", "id");
            else if (deviceLanguageCode.startsWith("ji"))
                patchedCode = deviceLanguageCode.replace("ji", "yi");
        }

        return patchedCode;
    }

}