HOME
Andrew Schwabe's Blog: Flex + Google Analytics - Fix Error #1009: Cannot access a property or method of a null object

Flex + Google Analytics - Fix Error #1009: Cannot access a property or method of a null object

Google has released a library for Flash and Flex to embed google analytics calls into your Flash/Flex app. You can find info and Google's sample code here: http://code.google.com/apis/analytics/docs/tracking/flashTrackingSetupFlex.html.

Since I use Flex, thats all I will cover here.

When I implemented Google's code, I got the "Error #1009: Cannot access a property or method of a null object" error that seems to show up from time to time. I knew it had to do with google analytics, since it was a fully working app before I added GA.

This very vague error means exactly what it says: you tried to do something with an object that wasn't initialized yet. I know this isn't helpful, but getting your brain around this will help you figure out what to do.

The error was being thrown in the code from Google's page in the onComplete() method here:


    tracker = new GATracker( this, "UA-111-222", "AS3", false );

In my case, everything in the code said that it SHOULD be working fine. So I said to myself, ok self, it should be initializing properly, but it isn't, so what can I do about it? What I came up with is, instead of initializing the GATracker in the component's onComplete() method, go to where I want to use the tracker object, and right before I use it, check to make sure that it is initialized. So I ended up with:


    // setup Google Analytics
    if (tracker == null)
        tracker = new GATracker( this, "UA-111-222", "AS3", false );
    tracker.trackPageview( "/your_ficticious_page/" );

And this worked perfectly :) Obviously the extra variable checking has the potential to introduces a small performance hit, but when it DOESN'T work one way, and DOES work another way, performance hit or no, we all tend to go the way that works :)


Comments (Comment Moderation is enabled. Your comment will not appear until approved.)