我从我的数据库中检索数据,将其放入自定义类DataClass
中,然后将mydata格式化为节点的ArrayList,直到这里一切都很好。然后,我想对我的数据进行循环,并将子节点添加到每个节点。但我有NullPointerException
错误......
所以我的课看起来像:
@Entity
public class DataClass {
@Id
private Integer id;
private String structureDescription;
private String structId;
private String structureTag;
private Integer elementId;
private String elementDescription;
private Integer elementsSuite;
private String elementTag;
private Integer parent;
private Integer elementTypeId;
然后我有一个Node类:
public class Node {
private String id = "-1";
private List<Node> children = null;
private String parent = "#";
private String text = "";
public Node(){}
public Node(String id, String parent, String text) {
this.id = id;
this.parent = parent;
this.text = text;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public List<Node> getChildren() {
return children;
}
public void setChildren(List<Node> children) {
this.children = children;
}
public void addChild(Node child)
{
children.add(child);
}
public String getParent() {
return parent;
}
public void setParent(String parent) {
this.parent = parent;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public boolean equals(Node node)
{
return node.getText().equals(getText());
}
}
所以我有一个方法将List of DataClass对象格式化为节点的arrayList:
public ArrayList<Node> formatData(List<DataClass> dbData)
{
ArrayList<Node> result = new ArrayList<>();
for(DataClass dbDataElement : dbData)
{
Node node = new Node();
node.setId(String.valueOf(dbDataElement.getId()) == null ? "" : String.valueOf(dbDataElement.getId()));
node.setParent(String.valueOf(dbDataElement.getParent()));
node.setText((dbDataElement.getElementTag() == null) ? dbDataElement.getStructId() : dbDataElement.getElementTag());
result.add(node);
}
return result;
}
然后我有一个方法应该找到每个节点的所有子节点:
public ArrayList<Node> addNodeChildren(ArrayList<Node> formattedNodes)
{
ArrayList<Node> result = new ArrayList<>();
for(Node parent: formattedNodes)
{
for(Node possibleChild: formattedNodes)
{
if(String.valueOf(parent.getId()).equals(possibleChild.getParent()))
{
parent.addChild(possibleChild);
}
}
}
return result;
}
但是当我从控制器拨打return mainService.addNodeChildren(mainService.formatData(dbData));
时出现此错误:
09-May-2017 11:06:18.498 SEVERE [http-nio-8080-exec-211] null.null An 由于异常映射器故障,未映射异常。 HTTP 500 响应将重新开始。
java.lang.NullPointerExceptionat be.groups.observatory.domainmodel.Node.addChild(Node.java:38) at be.groups.observatory.be.groups.observatory.services.MainService.addNodeChildren(MainService.java:37) at be.groups.ui.resource.StructureResource.getAllChildren(StructureResource.java:130)
答案 0 :(得分:1)
你从未发起过你的孩子实例,
有许多修复方法,其中一个方法是您可以将方法addChild
更改为:
public void addChild(Node child)
{
if(children==null){
children=new ArrayList<Node>();
}
children.add(child);
}