9
 //obtain the active page
 IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();

returns Exception in thread "Thread-3" java.lang.NullPointerExceptionµ. What shall i do?

Dominic Rodger
  • 97,747
  • 36
  • 197
  • 212

3 Answers3

39

If the thread does not run in the active window, PlatformUI.getWorkbench().getActiveWorkbenchWindow() will return "null". You must wrap your code in a Display, e.g.:

Display.getDefault().asyncExec(new Runnable() {
    @Override
    public void run() {
        IWorkbenchWindow iw = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
    }
});
Rudolf Widmann
  • 391
  • 3
  • 2
2

Add some null checks, it is possible for the workbench to not have an active window, not it is also possible for PlatformUI.getWorkbench to throw an IllegalStateException if the workbench is not yet started (e.g createAndRunWorkbench() has not yet been called).

IWorkbenchWindow window = PlatformUI.getWorkbench().getInstance()
    .getActiveWorkbenchWindow();

if(workbenchWindow != null) {
     IWorkbenchPage page = window .getActivePage();
}
Rich Seller
  • 83,208
  • 23
  • 172
  • 177
0

I have a work-around for this. even though its an old post.

    IWorkbench wb = PlatformUI.getWorkbench();
    if (wb.getWorkbenchWindowCount() == 1) {
      try{
      wb.getWorkbenchWindows()[0].getActivePage().getPerspective();
      }
      catch(NullPointerException e)
      {
        Logger.log(e);
      }
    }
Cheryl
  • 27
  • 1
  • 12