Header Sep

Java Tips, Tricks & Code

我的评分 用户评价
登录票选本页

January 2008

JSR 238, localize your data with Internationalization API

JSR 238, Internationalization API, provides the Java ME platform with locale-specific formatting of data, such as strings, numbers, currency and time and is found in Sony Ericsson's Java Platform 8 (JP-8) phones. This API differs from localization in that it requires more explicit actions to perform formatting. Below is an example MIDlet to try.

Download example MIDlet>>

The API basically consists of two parts. The first part handles formatting of date, time, currency, strings and more via method calls. The second part makes use of binary resource files to provide localized data.

The Formatter class and the StringComparator class can be used to format and compare locale-specific data. Supported locales can be queried by any of the classes.

String[] locales = Formatter.getSupportedLocales();
formatter formatter = new Formatter("en-US");
formatter.formatDate(calendarDateTime, style);
formatter.formatCurrency(currency);

StringComparator comparator = new StringComparator("en-US");
if(comparator.equals(string1, string2)){ … };

The above code is straightforward to use and does not require any external tools. This is however not true for the ResourceManager class. This class can be used to handle binary localized data. This is useful if a MIDlet wants to separate its localization mechanism from the program code.

In order to use this class, you must first use some external tools to generate binary data that can be understood by the ResourceManager. One way to do this is to use the Nokia ResourceMaker. The first thing you must do is to create an XML file containing all your strings and locales. Such an XML file is provided in the example that can be downloaded.

This text does not go into detail on how to generate these binary files, as it can be done in many ways and with existing documentation. More information on how to do this here>> 

Based on the XML file that the tool uses as input, a Java source file is generated for you to use in your program. This Java source file contains named indexes that are needed to extract the localized data from the binary files. It looks something like this:

public static final int WELCOME = 1;
public static final int TO = 2;

The names of the above variables are generated from your input in the XML file.

When you use the tool to generate the Java file and the binary files, you give it a base name used to identify this resource set. This name is used in your code to retrieve the ResourceManager instance.

ResourceManager manager = ResourceManager.getInstance("basename", "locale");
String localizedWelcome = manager.getString(BasenameClass.WELCOME);
String localizedTo = manager.getString(BasenameClass.TO);

You need a new ResourceManager instance for each locale.


More information:

我的评分 用户评价
登录票选本页