Avatar of Tolgar
Tolgar asked on

Null pointer exception in unselecting checkbox in Java?

Hi,
I am writing a code to unselect all checkboxes of a Tree.

When I click on a button in the GUI, it calls unselectAll method as below:

CheckListTree.getInstance().unselectAll();

Open in new window


CheckListTree class is like this. It has getInstance, unselectAll, checkPath, checkItems, and createCheckListTree methods.

When I print "instance" it is not null in line 7, but when I print "tree' in unselectAll method, it returns null in line 13. Therefore, I get this null pointer exception error.

But I don't know why it is null. Can you please take a look at it?



public class CheckListTree {
    private Tree tree;
   
    public static CheckListTree getInstance()
    {
        CheckListTree instance = new CheckListTree();
        System.out.println("instance: " + instance);
        return instance;
    }
    
    
    public void unselectAll (){
        System.out.println("tree: " + tree);
        for (TreeItem item : tree.getItems()) {   
            System.out.println("item: " + item);
            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() ) {
                Integer keyVal = (Integer) iter.next();
                //System.out.println("keyVal " + keyVal);
                String valFromKey = amap.get(keyVal);
                //System.out.println("valFromKey " + valFromKey);
                TreeItem itemI = new TreeItem(tree, SWT.NONE);
                itemI.setText(valFromKey);
              } 
            }
    }        
}

Open in new window


Thanks,
Java

Avatar of undefined
Last Comment
Tolgar

8/22/2022 - Mon
Melih SARICA

Before for each loop getitems instance to a variable and loop in that variable.  I think problem is object lcking issue
ASKER
Tolgar

But, tree is null. In that case getItems will not be able to get anything from the tree. So, I didn't understand how is it going to help if I assign getitems instance to a variable.

What do you think?
Melih SARICA

in line 13 u use variable tree.. but in getinstance u set a local variable instance.. u did nto set localvariable tree in getinstance function. set tree variable in getinstance function
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
ASKER
Tolgar

Can you please show me what you mean? I am a little confused.
ASKER
Tolgar

and I set tree in the beginning of the class

private Tree tree;

Open in new window


What is wrong with this? I use this variable in other methods in the same class but not in unselectAll method.
SOLUTION
Melih SARICA

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
SOLUTION
Log in to continue reading
Log In
Sign up - Free for 7 days
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
SOLUTION
Log in to continue reading
Log In
Sign up - Free for 7 days
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
ASKER CERTIFIED SOLUTION
Log in to continue reading
Log In
Sign up - Free for 7 days
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
ASKER
Tolgar

@mccarl: I made the changes that you recommended. And it worked fine.

Can you please point me to a good documentation to learn about these things in OOP?

Thanks,
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
mccarl

The Oracle Java tutorial/lessons are generally quite good, I think.

http://docs.oracle.com/javase/tutorial/java/index.html

Especially the lesson on OOP concepts, but a refresher on how that applies in Java is useful too. Now I realise that you obvious do know Java, and I don't mean to be condescending but I put that there because sometimes it is easy to get the general idea but it may be good to go back and make sure you really understand what is happening at a deeper level. In particular with all of this, make sure you really understand classes and objects and how they relate, how they are different, etc. Variables/members, as in class members, instance members, local variables, etc and their scope, including the use of the keyword static.

Then once you are happy with that, then I would also look at some general design patterns/best practices for working with OOP. Search Google for "object oriented best practices" and you will get lots of useful information on this. It will help you move from "adding just whatever code seems to make it work" to "structured code that is easy to maintain and add features too when needed".
ASKER
Tolgar

Thanks a lot.