title: Why am I getting this "Cannot access a property or method of a null object reference" error?
body: <p>I'm new to flex and actionscript. I'm trying to create a small flex app that has multiple states, but if I have nested containers, it looks like some of the objects are not getting initialized when I expected them to be, even when I have the creationPolicy set to "all."</p>
  
  <p>I've reduced the issue to a small example, with a commented block showing when it <em>does</em> work.</p>
  
  <p>Using the existing code, I get this error: "TypeError: Error #1009: Cannot access a property or method of a null object reference at main/init()" and the event handlers are not installed.</p>
  
  <p>If I instead use the commented block, which has the Panel and VBox elements removed, it <em>does</em> work.</p>
  
  <p>I know I could add a click attribute to the mxml elements, but this is just a simplified example, and I'm more interested knowing why the objects are not initialized when the app loads.</p>
  
  <pre><code>&lt;mx:Application 
    xmlns:mx="http://www.adobe.com/2006/mxml"
    applicationComplete="init();"
    currentState="start"&gt;
  
  &lt;mx:Script&gt;
    private function mainButtonHandler(event:Event):void{
      currentState = "start"
    }
  
    private function startButtonHandler(event:Event):void {
      currentState = "main";
    }
  
    public function init():void{
      mainButton.addEventListener(MouseEvent.CLICK, mainButtonHandler);
      startButton.addEventListener(MouseEvent.CLICK, startButtonHandler);
    }
  &lt;/mx:Script&gt;
  
  &lt;!-- this does not work --&gt;
  &lt;mx:states&gt;
    &lt;mx:State name="main"&gt; 
      &lt;mx:AddChild creationPolicy="all"&gt;
        &lt;mx:Panel creationPolicy="all"&gt;
          &lt;mx:VBox creationPolicy="all"&gt;
            &lt;mx:Button id="mainButton" label="Change to Start State"/&gt;
          &lt;/mx:VBox&gt;
        &lt;/mx:Panel&gt;
      &lt;/mx:AddChild&gt;
    &lt;/mx:State&gt;
  
    &lt;mx:State name="start"&gt; 
      &lt;mx:AddChild creationPolicy="all"&gt;
        &lt;mx:Panel creationPolicy="all"&gt;
          &lt;mx:VBox creationPolicy="all"&gt;
            &lt;mx:Button id="startButton" label="Change to Main state"/&gt;
          &lt;/mx:VBox&gt;
        &lt;/mx:Panel&gt;
      &lt;/mx:AddChild&gt;
    &lt;/mx:State&gt;
  &lt;/mx:states&gt;
  
  &lt;!-- this works --&gt;
  &lt;!--
  &lt;mx:states&gt;
    &lt;mx:State name="main"&gt; 
      &lt;mx:AddChild creationPolicy="all"&gt;
        &lt;mx:Button id="mainButton" label="Change to Start State"/&gt;
      &lt;/mx:AddChild&gt;
    &lt;/mx:State&gt;
  
    &lt;mx:State name="start"&gt; 
      &lt;mx:AddChild creationPolicy="all"&gt;
        &lt;mx:Button id="startButton" label="Change to Main state"/&gt;
      &lt;/mx:AddChild&gt;
    &lt;/mx:State&gt;
  &lt;/mx:states&gt;
  --&gt;
  
  &lt;/mx:Application&gt;
  </code></pre>
  
  <p>Thanks for any feedback.</p>