Java Reference
In-Depth Information
value must always be able to be stored and retrieved as a string. Therefore, it must be
possible to encode/decode all values into/from strings. A number of methods are
available to store and retrieve values as primitive types.
Preferences are per bundle
The preferences saved by one bundle are completely distinct from the preferences
saved by another bundle. The Preferences Service doesn't provide a mechanism for
one bundle to access another bundle's preferences storage. If this is needed, you
must obtain a reference to the source bundle's preferences in another way, such as
directly passing a reference to the other bundle.
Using the Preferences Service is straightforward. It's represented by the following sim-
ple interface:
public interface PreferencesService {
Preferences getSystemPreferences();
Preferences getUserPreferences(String name);
String[] getUsers();
}
The getSystemPreferences() method provides access to the system preferences root,
whereas the getUserPreferences() method provides access to a given user's prefer-
ences root. You can use the getUsers() method to enumerate all usernames that have
stored preferences.
When you have a node, you can navigate the preference tree using the children-
Names() , parent() , and node() methods on the returned Preferences node. For setting
values, the Preferences interface offers some simple methods to store key/value pairs:
public void put(String key, String value);
public void putInt(String key, int value);
public void putLong(String key, long value);
public void putBoolean(String key, boolean value);
public void putFloat(String key, float value);
public void putDouble(String key, double value);
public void putByteArray(String key, byte[] value);
For each of these methods, a corresponding getter method exists. Getter methods
always accept two arguments: the first to specify the key of the property to retrieve,
and the second to specify a default value in case the property doesn't exist (or in case
of errors). For instance:
public float getFloat(String key, float def);
Assuming you want to store the last time your bundle was started, you can do this
using the system preferences:
Preferences startPreferences =
service.getSystemPreferences().node("start");
startPreferences.putLong("time", new Date().getTime());
Search WWH ::




Custom Search