Question

This is my code:

public static String getLocalLanguage() {
    switch(Lang.valueOf(Locale.getDefault().getCountry().toLowerCase())) {
        case it:
        case de:
        case fr:
        case en:
        case pr:
        case sp:
            return Locale.getDefault().getCountry().toLowerCase();
        default:
            return "it";
    }
}

Lang is a enum type

public enum Lang {
    it,en,sp,fr,de,pr
}

Of course my code will throw an Exeception because if I call getLocalLanguage and Locale.getDefault returns some Enum Lang that doesn't exist (e.g. gb) will raise exeception..

So how can I fix this?
My target is to return just "it","de","fr","en","pr","sp" and if localLanguage is something else I want to return "it"..
Could you guys help me to achieve this?

Was it helpful?

Solution

Try this:

private static final Set<String> LANGUAGES = new HashSet<String>();
static {
    LANGUAGES.add("it");
    ... add the others ...
}

public static String getLocalLanguage() {
    String lang = Locale.getDefault().getCountry().toLowerCase();
    if (LANGUAGES.contains(lang)) {
        return lang;
    }
    return "it";
}

OTHER TIPS

try {
    Lang lang = Lang.valueOf(Locale.getDefault().getCountry().toLowerCase());
    return lang.toString();
} catch (IllegalArgumentException e) { // Thrown by Lang.valueOf when not found.
    Logger.getLogger(getClass().getName()).info("...");
    return "it";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top