To save and load preferences, an instance of IPreferenceStore
is typically obtained from the AbstractUIPlugin
subclass, in this case, the Activator
of the clock plug-in. The getPreferenceStore()
method returns a store which can be used to persist key/value pairs. Perform the following steps:
Activator
of the clock.ui
plug-in.start()
method to count the number of times the plug-in has been launched:int launchCount = getPreferenceStore().getInt("launchCount"); System.out.println("I have been launched "+ launchCount + "times"); getPreferenceStore().setValue("launchCount",launchCount+1);
The IPreferenceStore
is usually loaded via the AbstractUIPlugin
, which provides a getPreferenceStore()
. This API provides get/set methods for primitive types (getInt()
, getBoolean()
, getString()
, and so on) as well as setValue()
methods for the same types.
If the class does not have AbstractUIPlugin
subclass, it can also be acquired by using the following code:
IPreferenceStore preferenceStore = newScopedPreferenceStore(InstanceScope.INSTANCE,ID);
In the previous code, ID
is the name of the identifier prefix used, typically the bundle's ID. (In AbstractUIPlugin
it is calculated as bundle.getSymbolicName()
).
E4: If using E4, IPreferenceStore
can be obtained via injection. Alternatively, a single preference value can be bound with @Preference(name)
or @Preference
to get the IEclipsePreferences
object. It is also possible to track individual preferences being changed with a method parameter injection.
The number of times the plug-in is launched will be stored as a value in the preferences store. If run from Eclipse, the message, "I have been launched 0 times" is shown the first time the application is run; the second time, "I have been launched 1 times"; and each restart will update the counter.
Note that the preferences API generally shouldn't be used to store plug-in specific state. There's a method getStateLocation()
which returns an IPath
that can be used for storing such transient state.
If "I have been launched 0 times" is displayed repeatedly, Clear workspace before launching may be selected in the launch configurations menu. To disable this, go to Run | Run Configurations... and in the Main tab ensure that the Clear checkbox is deselected.