Q:

How to retain the state of a treeviewer in Java RCP application? 

I have a simple RCP application having couple of wizards out of which one is having a tree viewer.  I want to retain the state of the selected item in the tree viewer next time I open that particular view.  As of now I have implemented using static variables and its working fine. I want to know how it can be done in a better way? 
//Sample Code
private static RepositoryLocationItem lastRepoItemSelected;

Composite parent=new Composite(SWT.NONE)
treeViewer = new TreeViewer(parent);
treeViewer.setContentProvider(new MovingBoxContentProvider());
treeViewer.setLabelProvider(new MovingBoxLabelProvider());
treeViewer.setInput(getInitalInput());

treeViewer.addSelectionChangedListener(new ISelectionChangedListener() {

/* Setting the value of lastRepoItemSelected */
});

if(lastRepoItemSelected ! =null)
{
treeViewer.setSelection(new StructuredSelection(lastRepoItemSelected),true); 
}

A:

Assuming this is a 3.x style RCP (your view extends ViewPart) you can use the saveState method to save your view state:
@Override
public void saveState(final IMemento memento)
{
  // TODO set values in the 'memento'
}

You can then use the init method to restore values from the memento when the view is shown again:
@Override
public void init(final IViewSite site, final IMemento memento)
  throws PartInitException
{
  super.init(site, memento);

  // TODO restore from 'memento'
}

Note: Mementos are persisted across restarts of your RCP so you need to store values in them which are valid in a new instance of the RCP. 
Also look at the Eclipse wiki entry for more information. 
For a WizardPage you can use the IDialogSettings.  You must set this up in your Wizard using something like:
IDialogSettings pluginSettings = Activator.getDefault().getDialogSettings();
IDialogSettings wizardSettings = pluginSettings.getSection("id of your wizard");
if (wizardSettings == null) {
    wizardSettings= new DialogSettings("id of your wizard");
    pluginSettings.addSection(wizardSettings);
}
setDialogSettings(wizardSettings);

where Activator is your plugin activator class and "name of your wizard" is a id for your wizard (which can be anything as long as it is unique in your plugin). 
In your wizard page you can then get the settings with:
IDialogSettings settings = getDialogSettings();

IDialogSettings has lots of methods for saving and restore various sorts of values, such as:
settings.put("key", "string value");

String value = settings.get("key");

