I am facing error “NullPointExeption”, while trying to detect the user's selection in the eclipse plugin development

淺唱寂寞╮ 提交于 2020-01-24 01:35:09

问题


I am facing error "NullPointExeption", while trying to detect the user's selection in the eclipse plugin development. I have attached the code for both the classes, first, DetectSelection which detects the user's choice in the project explorer and second, SampleView which makes the custom plugin

Question that I asked Before : Eclipse Plugin: Get the class name on user's click/selection

After that it was working properly, but now I am again facing some errors: Now, I made DetectSelection class :

public class DetectSelection
 {
String classname ;
IPath packageName ;
private ISelection selection;

public void setSelection(ISelection iSelection) 
{
    this.selection = iSelection;
}

public void jk() 
{
    System.out.println(" HI!!!!");
    IWorkbenchPage page =PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
    IViewPart viewPart = page.findView("org.eclipse.jdt.ui.PackageExplorer");
    ISelectionProvider selProvider = viewPart.getSite().getSelectionProvider();
    selProvider.addSelectionChangedListener(new ISelectionChangedListener()
    {
        public void selectionChanged(SelectionChangedEvent event) 
        {
            if (!event.getSelection().isEmpty()) 
            {
                Iterator ite = ((IStructuredSelection) event.getSelection()).iterator();
                while (ite.hasNext()) 
                {
                    Object obj = ite.next();
                    String testString="";
                    if (obj instanceof IJavaElement) 
                    {
                        packageName= ((IJavaElement)obj).getPath();
                        System.out.println("getFileExtension()   "+ packageName.getFileExtension() );
                        String s= packageName.toString();
                        String s1[]= s.split("/");
                        if ("java".equals(packageName.getFileExtension()))
                        {
                            System.out.println("package name "+ s1[1]);
                            System.out.println("project name"+ ((IJavaElement)obj).getElementName());
                        }
                    }
                }
            }
        }
    });

 }
 }

This was working fine previously, when I made an object of this in the SampleView class and used it like this:

 public class SampleView extends ViewPart 
 {
public static final String ID = "typesview.views.SampleView";
private TableViewer viewer;
private Action action1;
private Action action2;
private Action doubleClickAction;

class ViewContentProvider implements IStructuredContentProvider
{
    public void inputChanged(Viewer v, Object oldInput, Object newInput) 
    {
    }
    public void dispose() 
    {
    }
    public Object[] getElements(Object parent) 
    {
        return new String[] { "One", "Two", "Three" };
    }
}
class ViewLabelProvider extends LabelProvider implements ITableLabelProvider {
    public String getColumnText(Object obj, int index) {
        return getText(obj);
    }
    public Image getColumnImage(Object obj, int index) {
        return getImage(obj);
    }
    public Image getImage(Object obj) {
        return PlatformUI.getWorkbench().
                getSharedImages().getImage(ISharedImages.IMG_OBJ_ELEMENT);
    }
}
class NameSorter extends ViewerSorter {
}

public SampleView() {
}

public void createPartControl(Composite parent) {
    **DetectSelection obj2 = new DetectSelection();
    obj2.jk();**
    viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
    viewer.setContentProvider(new ViewContentProvider());
    viewer.setLabelProvider(new ViewLabelProvider());
    viewer.setSorter(new NameSorter());
    viewer.setInput(getViewSite());

    PlatformUI.getWorkbench().getHelpSystem().setHelp(viewer.getControl(), "TYPESview.viewer");
    makeActions();
    hookContextMenu();
    hookDoubleClickAction();
    contributeToActionBars();
}
private void hookContextMenu() {
    MenuManager menuMgr = new MenuManager("#PopupMenu");
    menuMgr.setRemoveAllWhenShown(true);
    menuMgr.addMenuListener(new IMenuListener() {
        public void menuAboutToShow(IMenuManager manager) {
            SampleView.this.fillContextMenu(manager);
        }
    });
    Menu menu = menuMgr.createContextMenu(viewer.getControl());
    viewer.getControl().setMenu(menu);
    getSite().registerContextMenu(menuMgr, viewer);
}

private void contributeToActionBars() {
    IActionBars bars = getViewSite().getActionBars();
    fillLocalPullDown(bars.getMenuManager());
    fillLocalToolBar(bars.getToolBarManager());
}

private void fillLocalPullDown(IMenuManager manager) {
    manager.add(action1);
    manager.add(new Separator());
    manager.add(action2);
}

private void fillContextMenu(IMenuManager manager) {
    manager.add(action1);
    manager.add(action2);
    manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
}

private void fillLocalToolBar(IToolBarManager manager) {
    manager.add(action1);
    manager.add(action2);
}

private void makeActions() {
    action1 = new Action() {
        public void run() {
            showMessage("Action 1 executed");
        }
    };
    action1.setText("Action 1");
    action1.setToolTipText("Action 1 tooltip");
    action1.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().
        getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK));

    action2 = new Action() {
        public void run() {
            showMessage("Action 2 executed");
        }
    };
    action2.setText("Action 2");
    action2.setToolTipText("Action 2 tooltip");
    action2.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().
            getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK));
    doubleClickAction = new Action() {
        public void run() {
            ISelection selection = viewer.getSelection();
            Object obj = ((IStructuredSelection)selection).getFirstElement();
            showMessage("Double-click detected on "+obj.toString());
        }
    };
}

private void hookDoubleClickAction() {
    viewer.addDoubleClickListener(new IDoubleClickListener() {
        public void doubleClick(DoubleClickEvent event) {
            doubleClickAction.run();
        }
    });
}
private void showMessage(String message) {
    MessageDialog.openInformation(
        viewer.getControl().getShell(),
        "Sample View",
        message);
}

public void setFocus() {
    viewer.getControl().setFocus();
}
}

Now on running the plugin, I am getting the error:

java.lang.NullPointerException
at typesview.views.DetectSelection.jk(DetectSelection.java:40)
at typesview.views.SampleView.createPartControl(SampleView.java:58)
at org.eclipse.ui.internal.ViewReference.createPartHelper(ViewReference.java:375)
at org.eclipse.ui.internal.ViewReference.createPart(ViewReference.java:229)
at org.eclipse.ui.internal.WorkbenchPartReference.getPart(WorkbenchPartReference.java:595)
at org.eclipse.ui.internal.WorkbenchPage$ActivationList.setActive(WorkbenchPage.java:4317)
at org.eclipse.ui.internal.WorkbenchPage$18.runWithException(WorkbenchPage.java:3359)
at org.eclipse.ui.internal.StartupThreading$StartupRunnable.run(StartupThreading.java:31)
at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35)
at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:135)
at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:4140)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3757)
at org.eclipse.ui.application.WorkbenchAdvisor.openWindows(WorkbenchAdvisor.java:803)
at org.eclipse.ui.internal.Workbench$33.runWithException(Workbench.java:1600)
at org.eclipse.ui.internal.StartupThreading$StartupRunnable.run(StartupThreading.java:31)
at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35)
at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:135)
at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:4140)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3757)
at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:2609)
at org.eclipse.ui.internal.Workbench.access$4(Workbench.java:2499)
at org.eclipse.ui.internal.Workbench$7.run(Workbench.java:679)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:668)
at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:123)
at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:344)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:622)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:577)
at org.eclipse.equinox.launcher.Main.run(Main.java:1410)
at org.eclipse.equinox.launcher.Main.main(Main.java:1386)

Images to get the line numbers:

DetectSelection:

SampleView:


回答1:


The line numbers in the stacktrace and the screen-shot don't line up properly.

But in fact, the exception can only be thrown by the first five lines of the jk method anyway. (The rest is defining a callback method / object, and if an NPE was thrown by that code, the classname in the stack trace would be different.)

I suggest that you add some more trace-prints, or use the debugger to figure out which statement is actually throwing the exception ... and work backwards to the source of the null.


The javadoc for that method says:

Returns the view in this page with the specified id. There is at most one view in the page with the specified id.

Returns: the view, or null if none is found

If you are getting a null from the cause, it follows that the id parameter is not correct.

This may or may not be relevant, but you are passing "org.eclipse.jdt.ui.PackageExplorer" to find, but the ID for your SampleView class is "typesview.views.SampleView".



来源:https://stackoverflow.com/questions/20951044/i-am-facing-error-nullpointexeption-while-trying-to-detect-the-users-selecti

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!