Time for action – persisting a value

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:

  1. Open the Activator of the clock.ui plug-in.
  2. Add the following to the 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);
  3. Run the Eclipse instance and open the Time Zone View.
  4. In the host Eclipse, open the Console view. It should say "I have been launched 0 times".
  5. Close the Eclipse instance down and run it again (but do not clear the workspace). Open the Time Zone View again.
  6. In the host Eclipse open the Console view. It should now say "I have been launched 1 times".

What just happened?

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()).

Note

What just happened? 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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset