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

An update to this post can be found here

This was my first “bang my head against the wall for a really long time” Flex error. Here’s a simplified version of what I was doing wrong. I had a created a custom component which contained another Flex component.

<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml">
	<mx:Button id="button"/>
</mx:Canvas>

Then in my application I was using it as follows:

var myComp:MyComp = new MyComp();
myComp.button.label = "Button Label";
addChild( myComp );

The problem here has to do with what’s called the “component instantiation life cycle”. The basic issue is that when I was setting the label for the button it hadn’t yet been created. In the rest of the post I’ll cover three ways to fix this.

Solution 1 (don’t actually do this, just showing what’s possible)

The easiest way to fix this is to just add the component to the stage before setting the label.

var myComp:MyComp = new MyComp();
addChild( myComp );
myComp.button.label = "Button Label";

As you can see we’ve simply swapped lines 2 and 3. This is definitely not best practice. While it does work it means that you need to display your component before making any changes to it. This will be pretty inefficient as it will require the Flash player to update the component a second time.

Solution 2 (this one’s pretty good)

A better way to do this would be to add a variable to the custom component which stores the label. Then when the component is added to the stage it sets the button’s label to the value set. Here’s what it would look like

<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" initialize="init()">

	<mx:Script>
		<![CDATA[
			
			private var _buttonLabel:String;
			
			private function init():void
			{
				button.label = _buttonLabel;
			}
			
			public function set buttonLabel( value:String ):void
			{
				_buttonLabel = value;
			}
					
		]]>
	</mx:Script>
	
	
	<mx:Button id="button"/>
</mx:Canvas>

One thing worth pointing out is we’re using the initialize event rather than the creationComplete event. Setting the label for the button will cause the Flash player to recalculate the size of the button. If we used the creationComplete event it will have already measured the button. This means we’ll be forcing the player to measure it again.

To use this component we’d change the code slightly to use the new buttonLabel parameter:

var myComp:MyComp = new MyComp();
myComp.buttonLabel = "Button Label";
addChild( myComp );

Solution 3 (the real way to do it)

The catch with the 2nd solution is it only enables you to set the button label before you add the component to the stage. We could work around that by checking if the button already exists when setting the value for buttonLabel but we’re going to skip past that change and just implement it the real way.

<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml">

	<mx:Script>
		<![CDATA[
			
			private var _buttonLabel:String;
			private var _buttonLabelChanged:Boolean;
			
			public function set buttonLabel( value:String ):void
			{
				_buttonLabel = value;
				_buttonLabelChanged = true;
				
				invalidateProperties();
				invalidateSize();
			}
			
			override protected function commitProperties():void
			{
				super.commitProperties();
				
				if (_buttonLabelChanged)
				{
					button.label = _buttonLabel;
					_buttonLabelChanged = false;
				}
			}
					
		]]>
	</mx:Script>

	<mx:Button id="button"/>
</mx:Canvas>

By overriding the commitProperties function we enable the component to be far more efficient. The code which changes the button label will execute much quicker that the change will be displayed on screen. Using this approach even if we change the label many times, the Flash player will only recalculate the component once.

The purpose of the post was to show you how to resolve the “null object” error. While discussing this problem we’ve gotten in to the area of creating custom components but we’ve really just skimmed the surface. There are a ton of great tutorials online covering this topic in great depth. If you’d like to learn more a quick google search should find you everything you ever wanted to know (and probably more).

Best,
Hillel

Tags: , ,

30 responses to “Flex Error #1009: Cannot access a property or method of a null object reference”

  1. mark says :

    thanks nice post.

  2. Angel Arias says :

    I had the same problem. Thank you

  3. Alirio Boquin says :

    Hi there, I fix this error, in my case I’m using a TabNavigator and some customs components. I just change the property creationPolicy=”all”, the default value is “auto”. Read this this from Flex 3 Help: Containers with multiple views, such as the ViewStack and Accordion, do not immediately create all of their descendants, but only those descendants that are visible in the initial view. When you instantiate a navigator container, Flex creates all of the top-level children. For example, creating an Accordion container triggers the creation of each of its views, but not the controls within those views. The creationPolicy property determines the creation of the child controls inside each view.

    When you set the creationPolicy property to auto (the default value), navigator containers instantiate only the controls and their children that appear in the initial view. The first view of the Accordion container is the initial pane, as the following example shows:

    I hope this help a lot people.

    Bye

  4. Matus says :

    Thanks, useful post!

  5. Rick Re says :

    @Hillel

    Thanks Hillel. Probably a stupid question, but what if you have several things you need to set – would you need to modify the overridden commitProperties to handle all of them? (I’d think ‘yes’.) This seems like a bit of work.

    I also like Alirio’s approach (using setting the creationPolicy=”all”, but often times I don’t want to initialize all my view stack components until they are truly needed, so I’m not sure I want to use that.

  6. Rick R says :

    Somewhat related, and feel free to delete this later, but I’m going NUTS right now with this! Spending way too long on something that should be SOOO simple. I’d post on the flex forums, but can’t get to the site today, so maybe someone here has an idea what’s wrong with this since it’s a related issue.

    I have a viewstack which one component in the stack has another viewstack.

    For both of them I have creationPolicy=”all”

    However, the first time you click on a simple form field I get an error about “Cannot access a property or method of a null object reference.” It’s coming from the focusManager where _defaultButton is obviously null – but no clue why I even need a default button (yet even when I add deafultButton=”${submitButton}” to the form, I still get the error.

    Here is a post of some relavent code snippets. It seems so simple, yet I’m stumped… http://pastie.org/610012

    • Rick R says :

      ARGHGHHHHHH I’ve been going nuts seriously for the entire day including some last night – and it turns out the code works fine in Safari (and an old IE6 I have on old windows box), but craps out on my Mac with FF – which is supposedly using flashplayer 10 ?

      As an example. Here is a stripped down version showing the problem (pardon all the commented out code)

      http://dl.getdropbox.com/u/86998/EmployeeMaintenanceTest.zip

      I’m going to try to test on a different windows machine on FF to see what the issue is. I still must have something ‘bad’ in the code though for this not to have come up for someone else.

  7. Rick R says :

    Sorry for the late reply Hillel, it’s funny the issue is its a bug in flex 3.4. I ended up posting to the forums about it willing to give someone 50 bucks to figure out the issue (oh and to see the problem when you run the example is after you login simply click in the txt field. What sdk were you using? Maybe the bug was introduced later in the sdk3.4?)

    Anyway the description of the problem I was having and the workaround solution is found here:
    http://forums.adobe.com/thread/489164?tstart=90

    Thanks for your forum post and your willingness to help. (not sure why I didn’t get a notice of your follow up reply in this post thread.)

  8. Fatima Abeta says :

    You wouldn’t believe it but I’ve wasted all day digging for some articles about this. You’re a lifesaver, it was an excellent examine and has aided me out to no end. Cheers

  9. Sukanya says :

    TypeError: Error #1009: Cannot access a property or method of a null object reference.
    at mx.charts.chartClasses::ChartLabel/updateDisplayList()[C:\work\flex\dmv_automation\projects\datavisualisation\src\mx\charts\chartClasses\ChartLabel.as:262]
    at mx.core::UIComponent/validateDisplayList()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\core\UIComponent.as:6351]
    at mx.managers::LayoutManager/validateDisplayList()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\managers\LayoutManager.as:622]
    at mx.managers::LayoutManager/doPhasedInstantiation()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\managers\LayoutManager.as:695]
    at Function/http://adobe.com/AS3/2006/builtin::apply()
    at mx.core::UIComponent/callLaterDispatcher2()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\core\UIComponent.as:8628]
    at mx.core::UIComponent/callLaterDispatcher()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\core\UIComponent.as:8568]

    Above is the AS error ,plz let me know where Iam wrong

  10. Kim Johns says :

    Thank you a lot, wonderful job! It was the thing I required to get. When I click your RSS feed it seems to become a ton of garbled text, is the malfunction on my side?

  11. Sukanya says :

    Iam getting the following error when trying to download a excel file from a remote server:
    Error #2044: Unhandled IOErrorEvent:. text=Error #2038: File I/O Error.
    at com.example.programmingas3.fileio::FileDownload/init()[C:\Users\m1011995\Documents\Flex Builder 3\filedwnld\src\com\example\programmingas3\fileio\FileDownload.as:34]
    at FileIO/__fileDownload_creationComplete()[C:\Users\m1011995\Documents\Flex Builder 3\filedwnld\src\FileIO.mxml:11]
    at flash.events::EventDispatcher/dispatchEventFunction()
    at flash.events::EventDispatcher/dispatchEvent()
    at mx.core::UIComponent/dispatchEvent()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\core\UIComponent.as:9298]
    at mx.core::UIComponent/set initialized()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\core\UIComponent.as:1169]
    at mx.managers::LayoutManager/doPhasedInstantiation()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\managers\LayoutManager.as:718]
    at Function/http://adobe.com/AS3/2006/builtin::apply()
    at mx.core::UIComponent/callLaterDispatcher2()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\core\UIComponent.as:8628]
    at mx.core::UIComponent/callLaterDispatcher()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\core\UIComponent.as:8568]

  12. yasar says :

    saved me a lot of times.. thanks..

  13. Sunil says :

    Good post. i have just started learning AS and Flex and found this quite helpful

  14. evan says :

    Very nice approach, I resolved with the first solution, I consider it’s very good: Until the graphic object has not a parent, sounds logical now to be null… Once it’s attached somewhere, is not null. So I just invert the order and I resolved. Thanks!!!

    my wrong code:
    for each (var realEstate:XML in realEstates) {
    var oneRealEstate:MyRealEstateGUI = new MyRealEstateGUI ();
    oneRealEstate.setData(realEstate);
    reSection.addChild(oneRealEstate);
    }

    my code after the correction :
    for each (var realEstate:XML in realEstates) {
    var oneRealEstate:MyRealEstateGUI = new MyRealEstateGUI ();
    reSection.addChild(oneRealEstate); // by reference .!
    oneRealEstate.setData(realEstate);
    }

  15. Prakash.C says :

    we can use canvas.initialize(); also to initialize the components.

Trackbacks / Pingbacks

  1. autobuild it - October 30, 2011
  2. Vlasic - November 10, 2011

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: