tags:

views:

316

answers:

4

Is there a neat way of getting a Locale instance from its "programmatic name" as returned by Locale's toString() method? An obvious and ugly solution would be parsing the String and then constructing a new Locale instance according to that, but maybe there's a better way / ready solution for that?

The need is that I want to store some locale specific settings in a SQL database, including Locales themselves, but it would be ugly to put serialized Locale objects there. I would rather store their String representations, which seem to be quite adequate in detail.

A: 

It looks like you have the best answer

Xavier Combelle
This doesn't help much, but thanks for the support anyway ;)
Joonas Pulakka
+1  A: 

There doesn't seem to be a static valueOf method for this, which is a bit surprising.

One rather ugly, but simple, way, would be to iterate over Locale.getAvailableLocales(), comparing their toString values with your value.

Not very nice, but no string parsing required. You could pre-populate a Map of Strings to Locales, and look up your database string in that Map.

skaffman
Ah, the iteration might be quite a reasonable solution. Indeed it's surprising that Locale doens't have a static method for this.
Joonas Pulakka
+4  A: 

See the Locale.getLanguage() , Locale.getCountry().. store this combination in the database instead of the "programatic name"... when u want to build the Locale back, use public Locale(String language, String country)

here is a sample code, :)

// may contain simple syntax error, i dont have java rite now to test.. but this is a bigger picture for ur algo...
public String localeToString(Locale l)
{
    return l.getLanguage() + "," + l.getCountry();
}

public Locale stringToLocale(String s)
{
    StringTokenizer tempStringTokenizer = new StringTokenizer(s,",");
    if(tempStringTokenizer.hasMoreTokens())
    String l = tempStringTokenizer.nextElement();
    if(tempStringTokenizer.hasMoreTokens())
    String c = tempStringTokenizer.nextElement();
    return new Locale(l,c);
}
echo
Very good thinking, thanks!
Joonas Pulakka
+1  A: 

Well, I would store instead a string concatenation of Locale.getISO3Language(), getISO3Country() and getVariant() as key, which would allow me to latter call Locale(String language, String country, String variant) constructor.

indeed, relying of displayLanguage implies using the langage of locale to display it, which make it locale dependant, contrary to iso language code.

As an example, en locale key would be storable as

en_EN
en_US

and so on ...

Riduidel