Sunday, November 22, 2009

What did I learn today - Using ArrayContentProvider (Eclipse RCP - JFace)

If your table view displays a collection of objects for example, collection of Person objects, Collection of Employee info etc., instead of writing your own content provider, consider using ArrayContentProvider. This takes the viewer input (collection) and converts it to an Array.

For example, say your code does something like this:

this.viewer.setContentProvider(new EmployeeInfoContentProvider());
this.viewer.setLabelProvider(new EmployeeInfoLabelProvider());
// Assume employeeInfoSet is a Set of EmployeeInfo objects
this.viewer.setInput(this.employeeInfoSet);

EmployeeInfoContentProvider code:

public class EmployeeInfoContentProvider implements IStructuredContentProvider {

@Override
public Object[] getElements(final Object inputElement) {
if (inputElement instanceof Set) {
return ((Set) inputElement).toArray();
}

return new Object[0];
}

@Override
public void dispose() {
//Nothing to do
}

@Override
public void inputChanged(final Viewer viewer, final Object oldInput, final Object newInput) {
//Nothing to do
}

}

In the above code, EmployeeContentProvider does nothing but translating the collection to array. In this case, you can remove EmployeeContentProvider and use ArrayContentProvider, which does the conversion for you. So, your view code would look like this:

// Replacing EmployeeInfoContentProvider with ArrayContentProvider
this.viewer.setContentProvider(new ArrayContentProvider());
this.viewer.setLabelProvider(new EmployeeInfoLabelProvider());
// Assume employeeInfoSet is a Set of EmployeeInfo objects
this.viewer.setInput(this.employeeInfoSet);

Less code is better right!

No comments: