Solved

How to fix null pointer exception issue in Java?

Posted on 2013-11-25
3
338 Views
Last Modified: 2013-11-29
Hi,
My Java GUI code crashes in LINE 2 in this code snippet only in MAC.

         
           } else if (event.type == 13) { //type 13 means mouse down
                    		String item = event.item.toString();
                    		displayHelp(item, compTab2);

Open in new window


The action that I do is selecting an item from a tree and then collapsing the whole tree.


The error message that I get is:

Exception in thread "main" java.lang.reflect.InvocationTargetException
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
2013-11-25 16:21:45.735 java[4544:250b] An uncaught exception was raised
	at java.lang.reflect.Method.invoke(Method.java:597)
	at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)
Caused by: java.lang.NullPointerException
	at com.something.CheckListTree$1.handleEvent(CheckListTree.java:123)2013-11-25 16:21:45.735 java[4544:250b] Java exception occurred

	at org.eclipse.swt.widgets.EventTable.sendEvent(Unknown Source)
	at org.eclipse.swt.widgets.Display.sendEvent(Unknown Source)
	at org.eclipse.swt.widgets.Widget.sendEvent(Unknown Source)
	at org.eclipse.swt.widgets.Widget.sendEvent(Unknown Source)
	at org.eclipse.swt.widgets.Widget.sendEvent(Unknown Source)
	at org.eclipse.swt.widgets.Widget.notifyListeners(Unknown Source)
	at org.eclipse.swt.widgets.Display.runDeferredEvents(Unknown Source)
	at org.eclipse.swt.widgets.Display.readAndDispatch(Unknown Source)
	at com.something.Gui.main(Gui.java:682)
	... 5 more

Open in new window



Why does this happen and how can I fix it?



If you want to see the whole code for this methods: (LINE 31)

public void createCheckListTree(final Composite compTab2, GridData layoutData, List<CheckDBDetail> checkList)  {
    	     final Map<Integer, String> checkNameMap= new HashMap<Integer, String>();
            tree = new Tree(compTab2, SWT.CHECK | SWT.V_SCROLL);
            tree.setLayoutData(layoutData);
            tree.addListener(SWT.Selection, new Listener() {
                public void handleEvent(Event event) {
                    if (event.detail == SWT.CHECK) {
                        TreeItem item = (TreeItem) event.item;
                        boolean checked = item.getChecked();
                        checkItems(item, checked);
                        checkPath(item.getParentItem(), checked, false);
                        
                        //this is to test a bug
                        //Map<Integer, String> junk = getCheckedStandards(checkListMap, checkNameMap);
                        
                        //This is to disable the button if a checkbox is not selected
                        Map<Integer, String> checkedList = getCheckedStandards(checkListMap, checkNameMap);
                        //If there is a file and check then enable the related buttons 
                        if (Gui.txt.getText().trim().length() > 0 && checkedList.size() > 0){
                        	Gui.item_SaveSelections.setEnabled(true);
                        	Gui.item_RunChecks.setEnabled(true);
                        } else if(checkedList.size() > 0) {
                        	Gui.item_SaveSelections.setEnabled(true);
                        }else{
                        	Gui.item_SaveSelections.setEnabled(false);
                        	Gui.item_RunChecks.setEnabled(false);
                        }
//                        //get the list of checks from the checks list in Checks TAB
//                        getCheckedStandards(checkListMap, checkNameMap); 
                    } else if (event.type == 13) { //type 13 means mouse down
                    		String item = event.item.toString();
                    		displayHelp(item, compTab2);
                    } 
                }
            });
            

            TreeItem item_MtStandards = new TreeItem(tree, SWT.NONE);
            item_MtStandards.setText("Coding Standards");    
            
            TreeItem item_MtCppStandards = new TreeItem(item_MtStandards, SWT.NONE);
            item_MtCppStandards.setText("C/C++ Standards");

            TreeItem item_MtXXXStandards = new TreeItem(item_MtStandards, SWT.NONE);
            item_MtXXXStandards.setText("XXX Standards");

            TreeItem item_MtOtherStandards = new TreeItem(item_MtStandards, SWT.NONE);
            item_MtOtherStandards.setText("Other Standards");
            
            Iterator<CheckDBDetail> checkListIter = checkList.iterator();
            while(checkListIter.hasNext()) {
              CheckDBDetail checkDetail = checkListIter.next();

              if (checkDetail.getType().equals("cpp") || checkDetail.getType().equals("c")){
                TreeItem item_MtCppSubstandards = new TreeItem(item_MtCppStandards, SWT.NONE);
                item_MtCppSubstandards.setText(checkDetail.getName());
              } else if (checkDetail.getType().equals("XXX")){
                TreeItem item_MtJavaSubstandards = new TreeItem(item_MtXXXStandards, SWT.NONE);
                item_MtJavaSubstandards.setText(checkDetail.getName());
              } else {
                 TreeItem item_MtOtherSubstandards = new TreeItem(item_MtOtherStandards, SWT.NONE);
                item_MtOtherSubstandards.setText(checkDetail.getName());
              }
            }
            //expand the top level of the tree 
            tree.getItems()[0].setExpanded(true);
    } 

Open in new window


Thanks,
0
Comment
Question by:Tolgar
3 Comments
 
LVL 8

Expert Comment

by:mnrz
ID: 39676204
What is the code for
com.something.CheckListTree$1.handleEvent(CheckListTree.java:123)
?

if it is the inner class (listener) then which line is 123?

if (String item = event.item.toString();) is line 123
then that means 'item' is null in event OR toString() caused the NPE

Have you debugged the code to see what is null over there?

When you say 'only in Mac', do you mean it works fine in Windows? Have you tested it in other OS?

Give us more information please.
0
 
LVL 15

Expert Comment

by:ChloesDad
ID: 39676209
I suspect that Event.item is nothing, therefore you get a null reference exception when you try to call Tostring.

You can confirm this by using a breakpoint at the offending line and seeing what event.item is.

As to how to fix it, if event.item should be not null then the error is probably in the code that raised the event rather than the event handler.
0
 
LVL 35

Accepted Solution

by:
mccarl earned 500 total points
ID: 39676248
A few things first...  (event.type == 13) { //type 13 means mouse down is wrong. event.type == 13 is actually the "Selection" event which also makes sense because line 5 of the above, you are only adding this listener to listen for SWT.Selection events anyway. Which also means that you can just get rid of that part of the if statement as that should never be false, ie. because you are only listening for Selection events you will never have an event that has a type != 13.

And on to the problem at hand, event.item must be null to cause that exception. The reason why you are getting a different results depending on OS, is because most of the SWT is just some Java code that wraps the actual components that the underlying OS provides. So in the situation that you are describing, ie. "selecting an item from a tree and then collapsing the whole tree", Windows must fire an event that still has the "item" set to some widget that is in your GUI whereas Mac fires the event with nothing selected and so event.item == null. It should be no big deal, just check for it. So the resultant code, with both changes applied, should be something like...
public void createCheckListTree(final Composite compTab2, GridData layoutData, List<CheckDBDetail> checkList)  {
    	     final Map<Integer, String> checkNameMap= new HashMap<Integer, String>();
            tree = new Tree(compTab2, SWT.CHECK | SWT.V_SCROLL);
            tree.setLayoutData(layoutData);
            tree.addListener(SWT.Selection, new Listener() {
                public void handleEvent(Event event) {
                    if (event.detail == SWT.CHECK) {
                        TreeItem item = (TreeItem) event.item;
                        boolean checked = item.getChecked();
                        checkItems(item, checked);
                        checkPath(item.getParentItem(), checked, false);
                        
                        //this is to test a bug
                        //Map<Integer, String> junk = getCheckedStandards(checkListMap, checkNameMap);
                        
                        //This is to disable the button if a checkbox is not selected
                        Map<Integer, String> checkedList = getCheckedStandards(checkListMap, checkNameMap);
                        //If there is a file and check then enable the related buttons 
                        if (Gui.txt.getText().trim().length() > 0 && checkedList.size() > 0){
                        	Gui.item_SaveSelections.setEnabled(true);
                        	Gui.item_RunChecks.setEnabled(true);
                        } else if(checkedList.size() > 0) {
                        	Gui.item_SaveSelections.setEnabled(true);
                        }else{
                        	Gui.item_SaveSelections.setEnabled(false);
                        	Gui.item_RunChecks.setEnabled(false);
                        }
//                        //get the list of checks from the checks list in Checks TAB
//                        getCheckedStandards(checkListMap, checkNameMap); 
                    } else {
                           if (event.item != null) {
                    		String item = event.item.toString();
                    		displayHelp(item, compTab2);
                           }
                    } 
                }
            });
            

            TreeItem item_MtStandards = new TreeItem(tree, SWT.NONE);
            item_MtStandards.setText("Coding Standards");    
            
            TreeItem item_MtCppStandards = new TreeItem(item_MtStandards, SWT.NONE);
            item_MtCppStandards.setText("C/C++ Standards");

            TreeItem item_MtXXXStandards = new TreeItem(item_MtStandards, SWT.NONE);
            item_MtXXXStandards.setText("XXX Standards");

            TreeItem item_MtOtherStandards = new TreeItem(item_MtStandards, SWT.NONE);
            item_MtOtherStandards.setText("Other Standards");
            
            Iterator<CheckDBDetail> checkListIter = checkList.iterator();
            while(checkListIter.hasNext()) {
              CheckDBDetail checkDetail = checkListIter.next();

              if (checkDetail.getType().equals("cpp") || checkDetail.getType().equals("c")){
                TreeItem item_MtCppSubstandards = new TreeItem(item_MtCppStandards, SWT.NONE);
                item_MtCppSubstandards.setText(checkDetail.getName());
              } else if (checkDetail.getType().equals("XXX")){
                TreeItem item_MtJavaSubstandards = new TreeItem(item_MtXXXStandards, SWT.NONE);
                item_MtJavaSubstandards.setText(checkDetail.getName());
              } else {
                 TreeItem item_MtOtherSubstandards = new TreeItem(item_MtOtherStandards, SWT.NONE);
                item_MtOtherSubstandards.setText(checkDetail.getName());
              }
            }
            //expand the top level of the tree 
            tree.getItems()[0].setExpanded(true);
    } 

Open in new window

0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Since upgrading to Office 2013 or higher installing the Smart Indenter addin will fail. This article will explain how to install it so it will work regardless of the Office version installed.
If you’re thinking to yourself “That description sounds a lot like two people doing the work that one could accomplish,” you’re not alone.
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

759 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

26 Experts available now in Live!

Get 1:1 Help Now