0

I am trying to create an editable TreeTableView from a XML Document. For this, i am wrapping the Elements from the Document within a class. The Data of the Elements is stored within the attributes key and val. My Wrapper consists of

private Element node;

private final StringProperty key = new SimpleStringProperty(this,  node.getAttribute("key"), "temp");
private final StringProperty val = new SimpleStringProperty(this, node.getAttribute("val"), "temp");

public ElementWrapper(Element n){
    System.out.println("creating element "+n.getNodeName());
    node = n;
}
public String getKey(){
    return key.get();
}
@Override
public String getVal(){
    return key.get();
}
public void setKey(String key){
    ((Element)node).setAttribute("key", key);
}
@Override
public void setVal(String value){
    ((Element)node).setAttribute("val", value);
}
@Override
public Element getElement(){
    return node;
}
@Override
public StringProperty keyProperty(){
    return key;
}
@Override
public StringProperty valProperty(){
    return val;
}

I wrote a recursive algorithm which creates the tree items and sets them with

TreeItem<NodeWrapper> newsub = new TreeItem<>(new ElementWrapper(current));

where current is the XML Element. At this Point i get a NullPointerException for lib.ElementWrapper.<init>(ElementWrapper.java:21) which is the second line of the Wrapper class posted above. How do i set this correctly?

Andrii Abramov
  • 10,019
  • 9
  • 74
  • 96
chenino
  • 454
  • 2
  • 7
  • 19

1 Answers1

3

Change it to:

private Element node;

private final StringProperty key;
private final StringProperty val;

public ElementWrapper(Element n){
    System.out.println("creating element " + n.getNodeName());
    node = n;
    key = new SimpleStringProperty(this, node.getAttribute("key"));
    val = new SimpleStringProperty(this, node.getAttribute("val"));
}

Because these initializations are done before executing costructor:

private final StringProperty key = new SimpleStringProperty(this,  node.getAttribute("key"), "temp");
private final StringProperty val = new SimpleStringProperty(this, node.getAttribute("val"), "temp");

Here is nice question about initialization: Java order of Initialization and Instantiation.
Official documentation: Initializing Fields.

Community
  • 1
  • 1
Andrii Abramov
  • 10,019
  • 9
  • 74
  • 96
  • Well this seems to be the reason with the Null Pointer, only Problem i got now is the elements wont be set with the desired value from the Attribute. maybe i got to figure out why they only see the initial value – chenino Nov 23 '16 at 14:47
  • @chenino Sorry, could you provide more details what is wrong ? – Andrii Abramov Nov 23 '16 at 14:50
  • Found the solution already, did an edit to your answer and marked it. If i set the last value on the constructur to null, values wouldnt be updated on the tree table. fixed this, now everythign is working for me. Thank you very much Andrii! – chenino Nov 23 '16 at 14:59