0

I am attempting to write a listener for when a new item is selected on a ListView Node. But the problem is I get a NPE when I run the application. From looking at it I am assuming that this may be being thrown because the list is empty upon run time, but I have no clue how to fix it.

Update 1: From further investigation, with a btn action listener I am writing. When I tried to access the selected item, I was thrown a null pointer exception. Work around was wrapping it with a try/catch, which ultimately fixed it. Will try something similar with viewList and see if it will work

Update 2: try/catch(NPE) workaround worked for the viewList action Listener

Code at Line 186: ListView.getSelectionModel().selectedItemProperty().addListener(new...

listView = new ListView<BusinessCard>();
observableList = FXCollections.observableList(cardModel.getCards());
//cardModel.getCards() -> ArrayList<BusinessCards>

// ListView Listener, changes text fields for the selected B.C in ViewLsit
            listView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<BusinessCard>() {
                @Override
                public void changed(ObservableValue<? extends BusinessCard> arg0, BusinessCard oldval,BusinessCard newVal) {
                    if(newVal != null) setDataFields(newVal.getUI());       
                }
            });
Javant
  • 1,009
  • 10
  • 17
  • 1
    Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Tom Jun 29 '16 at 15:01
  • 2
    I don't think it's a duplicate. This is a specific question about a JavaFX problem. – A. L. Flanagan Jun 29 '16 at 15:08
  • Line 186 does not consist of 10 lines. Which one is 186? – Tim Jun 29 '16 at 15:09
  • For `listView.getSelectionModel().selectedItemProperty().addListener(...` to throw this exception `listView` would need to be `null` (either that or one of the chained method calls return `null`, which doesn't happen with the standard `ListView`) – fabian Jun 29 '16 at 15:38
  • The question is valid and it is not duplicate of "What is a NullPointerException, and how do I fix it?" – G.V. Feb 13 '18 at 11:12

1 Answers1

3

When calling listView.getSelectionModel().selectedItemProperty()... and the view list was empty, null was being thrown. Which is said to be a behavior in the documentation

Workaround:

// ListView Listener, changes text fields for the selected B.C in ViewList

            listView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<BusinessCard>() {
                @Override
                public void changed(ObservableValue<? extends BusinessCard> arg0, BusinessCard oldval,BusinessCard newVal) {
                    if(newVal == null) return;
                    setDataFields(newVal.getUI());      
                }
            });
Javant
  • 1,009
  • 10
  • 17