0

I want to fetch data if a specific element of a tree is expanded.

public void treeExpanded(TreeExpansionEvent event) {  
   Object element = event.getElement();
   if (element instanceof MyClass) {
      fetch.......
   }
} 

The problem is that the content provider seems to trigger getChildren() before the treeExpanded()-method so I get a NullPointerException everytime I expand the element because the content provider tries to use the data which is never fetched. How can i solve this properly?

Rüdiger Herrmann
  • 20,512
  • 11
  • 62
  • 79
Ubuntix
  • 324
  • 4
  • 15
  • I see you're new to SO. If you feel an answer solved the problem, please mark it as 'accepted' by clicking the green check mark. This helps keep the focus on older posts which still don't have answers. – Rüdiger Herrmann Jul 13 '15 at 19:32

2 Answers2

2

Your code should not depend on the order in which getChildren() and treeExpanded() is called. This is an implementation detail of the TreeViewer and may change in the future.

Fetch the elements to be shown in getChildren() or inputChanged() of the content provider.

If your fetch operation takes too long to be run in the UI thread, run it in a background thread and return a placeholder element that is replaced, once the fetch operation finishes. For an example, see the DeferredTreeContentManager of org.eclipse.ui.

Alternatively you can see if the JFace DeferredContentProvider fits your needs.

Rüdiger Herrmann
  • 20,512
  • 11
  • 62
  • 79
1

Yes the content provider getChildren is called before the treeExpanded event is fired. You cannot use this event to populate the tree.

If you want to delay getting parts of the tree perhaps you should be looking at a tree using the SWT.VIRTUAL flag and an ILazyTreeContentProvider content provider.

greg-449
  • 109,219
  • 232
  • 102
  • 145