Search code examples
actionscript-3flashapache-flexflex4

"null object reference" error in ActionScript 3


I used my app's resize handler to resize my component but it is throwing this error :

TypeError: Error #1009: Cannot access a property or method of a null object reference

Here is my code :

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
           xmlns:s="library://ns.adobe.com/flex/spark" 
           xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"
           resize="application2_resizeHandler(event)" >
    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
    </fx:Declarations>

    <fx:Script>
        <![CDATA[
            import mx.events.FlexEvent;
            import mx.events.ResizeEvent;

            private var employeeName:String = 'ravi';

            protected function application2_resizeHandler(event:ResizeEvent):void
            {
                mainGroup.width = stage.width - 10;
                mainGroup.x = 5;                    
            }

        ]]>
    </fx:Script>    
    <s:Group width="100%" height="100%">
        <s:VGroup id="mainGroup" >
            <s:Label id="employeeNameLabel" text="{employeeName}" />
            <s:Label id="departmentLabel"  />
        </s:VGroup>

        <s:Button id="getData" />
    </s:Group>
</s:Application>

Solution

  • You got the #1009 error because your resize event is fired before the creation of your objects. So, you should wait for that and that your app is added to the stage to be able to use the stage object.

    For that, I think that the best event is the applicationComplete event, then you can add a resize event to resize your component ...

    So you can do like this for example :

    <s:Application 
        xmlns:fx="http://ns.adobe.com/mxml/2009" 
        xmlns:s="library://ns.adobe.com/flex/spark" 
        xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"
        applicationComplete="application2_applicationCompleteHandler(event)" >
    

    then

    protected function application2_applicationCompleteHandler(event:FlexEvent):void
    {
        // if you want you can resize your component for the 1st time
        // by calling the application2_resizeHandler() function
        application2_resizeHandler(new ResizeEvent(ResizeEvent.RESIZE));
    
        // add the resize event listener to your app
        event.target.addEventListener(ResizeEvent.RESIZE, application2_resizeHandler);
    }
    

    Hope that can help.