R – Flex Tree Properties, Null Reference

apache-flextreexml

I am pulling down a large XML file and I have no control over it's structure.

I used a custom function to use the tag name to view the tree structure as a flex tree, but then it breaks. I am guessing it has something to do with my other function, one that calls attribute values from the selected node.

See code.

<mx:Tree x="254" y="21" width="498" height="579" id="xmllisttree"       labelFunction="namer" dataProvider="{treeData}" showRoot="false"  change="treeChanged(event)" />

//and the Cdata

import mx.rpc.events.ResultEvent; 
[Bindable] private var fullXML:XMLList;  
private function contentHandler(evt:ResultEvent):void{  
    fullXML = evt.result.page;  
}  

[Bindable]
public var selectedNode:Object;

public function treeChanged(event:Event):void {
selectedNode=Tree(event.target).selectedItem;
}

 public function namer(item:Object):String {
        var node:XML = XML(item);
        var nodeName:QName = node.name();
        var stringtest:String ="bunny";
            return nodeName.localName;
        }

The error is TypeError: Error #1009: Cannot access a property or method of a null object reference.

Where is the null reference?

Best Answer

OK. It sounds like your XML looks something like this:

<root>
  <test>
    <child>leaf 1</child>
  </test>
  <test2>
    <child2>leaf 2</child2>
  </test2>
</root>

The significant part of this is that there is simple content within the child and child2 tags. Expanding the tree to show 'leaf 1' or 'leaf 2' causes the error you are receiving, because node.name() will return null. This makes sense, because 'leaf 1' and 'leaf 2' are text nodes and don't have node names.

To correct the problem, you can update the namer function to something along these lines:

public function namer(item:Object):String {
    var node:XML = XML(item);
    var nodeName:QName = node.name();
    if (nodeName) {
        return nodeName.localName;
    } else {
        return String(node);
    }
}

This will use 'leaf 1' and 'leaf 2' as the label for the corresponding nodes in the tree.