How to solve null pointer exception error in Java?

Hi,
I have a code in Java and it returns the following error:

Exception in thread "main" java.lang.NullPointerException
	at com.something.tools.flows.standards.Gui.main(Gui.java:404)

Open in new window


This is code is in Gui.java (Line 404 is Line 8 in here)

        //TAB2 CONTENT
        //This is the checks check box tree 
        GridData checksGridData2 = new GridData(GridData.FILL_BOTH);
        QueryDatabase qrydb = new QueryDatabase();
        List<HashMap<Integer, String>> checkList = qrydb.getFullCheckList();
        System.out.println(checkList);
        CheckListTree clt = CheckListTree.getInstance();
        clt.createCheckListTree(compTab2, checksGridData2, checkList);
        new Label(compTab2, SWT.NONE);

Open in new window


The error is in line 8.

This is the code that I have in QueryDatabase class and I think this code runs fine. (I have the output value below the code):

public class QueryDatabase {
       
    public List<HashMap<Integer, String>> getFullCheckList() throws ClassNotFoundException, SQLException{
        Class.forName("com.mysql.jdbc.Driver") ;
        Connection conn = DriverManager.getConnection("jdbc:mysql://server/database", "database", "pwd") ;
        Statement stmt = conn.createStatement() ;
        String querycheckName = "SELECT `name`, `id` FROM `check`" ;
        ResultSet rs = stmt.executeQuery(querycheckName) ;
        ArrayList<HashMap<Integer, String>> checkList = new ArrayList<HashMap<Integer, String>>();
        while(rs.next()) {
            //System.out.println("rs: " + rs);
            HashMap<Integer, String> check = new HashMap<Integer, String>();
            Integer anId = rs.getInt("Id");
            String aName = rs.getString("Name");
            //System.out.println("anId : " + anId );
            //System.out.println("aName : " + aName );
            check.put(anId , aName );
            //System.out.println("check: " + rs);
            checkList.add(check);
        }
        rs.close();
        stmt.close();
        conn.close();
        //System.out.println("checkList:" + checkList);
        return checkList;
    }  

Open in new window


And this code can successfully return checkList as the following:

[{4=something1}, {183=something2}, {101=something3}, {105=something4}]

Open in new window


Then in line 8, I call createCheckListTree method from the CheckListTree class.

This is the CheckListTree class and createCheckListTree method which causes the null pointer exception error in Line 8 is in it:

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.eclipse.swt.*;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.*;

public class CheckListTree {
    private Tree tree;
    private static CheckListTree instance = null;
   
    
    private CheckListTree()
    {
        if (instance == null) {
            instance = new CheckListTree();
         }
    }
    
    public static CheckListTree getInstance()
    {
        return instance;
    }
    
    
    public void unselectAll (){
        for (TreeItem item : tree.getItems()) {    
            checkItems(item, false);
        }
        
    }
    
    public void checkPath(TreeItem item, boolean checked, boolean grayed) {
        if (item == null) return;
        if (grayed) {
            checked = true;
        } else {
            int index = 0;
            TreeItem[] items = item.getItems();
            while (index < items.length) {
                TreeItem child = items[index];
                if (child.getGrayed() || checked != child.getChecked()) {
                    checked = grayed = true;
                    break;
                }
                index++;
            }
        }
        item.setChecked(checked);
        item.setGrayed(grayed);
        checkPath(item.getParentItem(), checked, grayed);
    }

    public void checkItems(TreeItem item, boolean checked) {
        item.setGrayed(false);
        item.setChecked(checked);
        TreeItem[] items = item.getItems();
        for (int i = 0; i < items.length; i++) {
            checkItems(items[i], checked);
        }
    }

    public void createCheckListTree(Composite compTab2, GridData layoutData, List<HashMap<Integer, String>> checkList)  {
            tree = new Tree(compTab2, SWT.BORDER | SWT.CHECK);
            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);
                    }
                }
            });
                  
            
            Iterator<HashMap<Integer, String>> checkListIter = checkList.iterator();
            while(checkListIter .hasNext()) {
              HashMap<Integer, String> amap =   (HashMap<Integer, String>) checkListIter .next();
              Set<?> keysetString = (Set<?>) amap .keySet();
              Iterator<?> iter = keysetString.iterator();
              while( iter.hasNext() ) {
                String keyVal = (String) iter.next();
                String valFromKey = amap.get(keyVal);
                  TreeItem itemI = new TreeItem(tree, SWT.NONE);
                  itemI.setText("Check " + valFromKey);
              } 
            }
    }        
}

Open in new window



My first thought was that one of the inputs in line 8 is null.

I debugged the code and compTab2 didn't look null to me. compTab2's value is "Composite (id=53)"

This is how I create compTab2 in Gui.java in previous lines. (This should be ok because I have been using this piece of code for sometime and it was ok.)

Composite compTab2 = new Composite(folder, SWT.NULL);

Open in new window


Do you see what is wrong on this code so that it returns this null pointer exception?

It could be related with the constructor in CheckListTree class but I am not sure what is wrong.

Thanks,
TolgarAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

CPColinSenior Java ArchitectCommented:
I bet CheckListTree.getInstance() is returning null, since nobody has called the CheckListTree() constructor yet. That constructor, as currently written, will call itself infinitely and overflow your stack. You might want to move the "new CheckListTree()" call into getInstance() or into a static initializer block.
0
TolgarAuthor Commented:
@CPColin: I see what you mean. But I am kind of new to Java. Can you please shortly show me how I should do this?

Thanks,
0
TolgarAuthor Commented:
@CPColin: You are absolutely right. I debugged it again I saw that "getInstance" returns null so "clt" in line 7 is null.  I am waiting for your reply.

Thanks,
0
CPColinSenior Java ArchitectCommented:
The simplest way would be to do this:

    private static CheckListTree instance = new CheckListTree();

Open in new window


and remove the code in the CheckListTree() constructor. Since instance is static, it will be initialized the first time your code references the ChechListTree class.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.