Best Practices for ActionScript Event Listeners

I see a lot of incorrect instantiation of event listeners, and I’ve also done it wrong quite a few times myself, especially when coding really fast. Doing it right is easy and the following four steps could save you a ton of debugging time later. 

Step 1: First, create the object. In this case I’m creating a Timer object using the ActionScript flash.utils.Timer Class:  

var myTimer:Timer = new Timer(1000);

Step 2: Second, always add your event listeners before executing any of the objects methods. And always, always attach the event listener to an object. Simply calling an addEventListener without attaching it to an object means the listener will receive any events broadcast for that type of event. This can become a nightmare in projects that may have dozens or even hundreds of event listeners running and you have to debug a problem. 

//myTimer is the object to which we will attach the listener.
//timer is the type of listener we want to observe.
//And, timerHandler the function to call when the event occurs.
myTimer.addEventListener(“timer”,timerHandler);

Step 3: Third, now you can call the objects method. I’m going to call the start() method which will kick off the Timer: 

myTimer.start();

Step 4: Lastly, when you are done with an object, always remove the event listener. Leaving event listeners active when they aren’t needed can cause memory leaks. If an object is not removed, it is still registered and it will remain in memory. By removing the event listener, you’ll allow the garbage collector to eventually deallocate it from memory. 

    myTimer.removeEventListener(“timer”,timerHandler);

Why do things in this order? If you add your event listeners after calling a method, such as start(), you can potentially miss an event that occurs right before the event listener is created. By only calling methods after event listeners are created you eliminate the possibility of missing something and banging your head against the wall while trying to debug it under a heavy deadline. 

Here’s a complete Flex 4 sample app that you can play with to try it out: 

<?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">
 <fx:Script>
     <![CDATA[   

       private var myTimer:Timer;

       public function timerHandler(event:TimerEvent):void
       {
          var date:Date = new Date();
          textArea1.text = date.hours.toString()+
             ":"+date.minutes.toString()+
             ":"+date.seconds.toString()+
             ":"+date.milliseconds.toString();
       }   

       protected function start_clickHandler(event:MouseEvent):void
       {
           myTimer = new Timer(1000);
           myTimer.addEventListener("timer", timerHandler);
           myTimer.start();
       }

       protected function stop_clickHandler(event:MouseEvent):void
       {
           myTimer.stop(); 
           myTimer.removeEventListener("timer", timerHandler);
       }
  ]]>
 </fx:Script>

 <s:TextArea id="textArea1" x="15" y="70" width="270" height="20"/>
 <s:Button x="15" y="28" label="Start" click="start_clickHandler(event)"/>
 <s:Button x="103" y="28" label="Stop" click="stop_clickHandler(event)"/>
</s:Application>

Debugging with Flash Builder 4 – Flash Player Debugger Req’d

If you are just starting out with Adobe’s Flash Builder 4, or you installed it on a new machine, you’ll need to install the debug version of Flash Player for everything to work correctly. If you have the regular, non-debug version of the Player installed, the debugger in Flash Builder won’t be able to connect to Flash Player, it will either throw a warning or it will hang and then eventually time-out.

To find out what version of Flash Player you have installed, go here to Adobe’s Flash Player Version Checker. If your results look like this screenshot, you’ll need to upgrade.

To get the latest version of the Flash Player debugger version go here. Be sure to scroll down the page and look for the section that’s appropriate for your operating system. If you are using Firefox on Windows for example, then choose the Netscape-compatible option: http://www.adobe.com/support/flashplayer/downloads.html

If you are looking to uninstall Flash Player for troubleshooting, then you’ll want to read this Adobe Knowledge Base article.

Flash Builder Burrito makes Android mobile development easy

I had a brief encounter with Adobe’s Flash Builder Burrito during AdobeMAX. But this weekend was my chance to test drive it more fully and build an Android app from scratch. To be fair in this evaluation, I haven’t deployed a production-grade Android app…yet! I’ve really only touched the surface, and I’m sure there’s plenty of gotchas to come. But, first impressions are important and here are a few things I really liked about Flash Builder Burrito.

Likes

Very simple to get started. Check out the list of requirements:

  • Windows or Mac machine
  • FlashBuilder Burrito Preview Version

Take note that having an Android phone isn’t a requirement to get started, more on that in just a moment. If you do have an Android phone, then there are additional requirements:

  • Android with Froyo 2.2, AIR 2.5.x and/or Flash Player 10.1
  • USB driver for your model Android
  • Cable to attach your Android to your development machine
  • Network (for debugging)

At the time I’m writing this your deployment options include Flex, which will run in the Android’s Flash Player 10.1, or AIR 2.5.x, which runs locally on the device.

Makes use of existing Flex/ActionScript skills. I’m still very impressed with being able to use my existing Flex and ActionScript skills to essentially build a prototype mobile app in less than an hour and then deploy it to a phone for testing. When I first saw this at MAX it simply blew me away.

Built-in Emulator, no droid required. A very nice feature that Adobe added to Flash Builder Burrito is you don’t have to have an Android phone to get started building apps. It has a built-in emulator that currently lets you choose from 11 different Android platforms, such as Droid 2 and EVO. You can also easily switch from portrait view to landscape view to simulate turning your phone sideways. That was a simple thing, but a mandatory requirement for testing.

Sure, you’ll need a device to do field testing. For example, I wasn’t able to effectively use my emulator because my app required access to a device’s GPS. Once I deployed my test app to a device, then I was able to test the GPS functionality.

Dislikes

Granted this is a Preview release, there are still a few things I had problems with that would like to see added/changed in the final release.

Needs built-in advanced device debugging. The device debugging interface between Flash Builder Burrito and the Android phone is completely bare bones, absolutely no-frills…nada, zip. If you have any problem connecting to your phone it’s anyone’s guess as to what the actual problem is. You won’t get any useable feedback other than things won’t work. I spent four hours trying to troubleshoot why I couldn’t publish to my Droid 2, the launcher would simply hang.

I followed all the instructions carefully and rechecked them multiple times. I tried almost everything under the sun including multiple versions of the USB driver with reboot after reboot. I even installed the Android SDK and was able to successfully publish to my phone using the adb command-line interface. What finally fixed the problem was I upgraded the phone to AIR 2.5.1 on a whim. And presto, everything worked immediately!

It should be a requirement for Flash Builder to provide feedback about the device and provide hints on what might not be working and suggestions on how to solve the problem. Include something similar to adb devices, which would let me know that Flash Builder even recognizes the Android via USB. I’d also like to see something built-in similar to adb logcat that can provide real-time device feedback for every action that happens on the phone.  

Simplify the Android configurations. In Flash Builder Burrito, you have three specific configuration windows underneath the “Run” option. You have Profile, Run and Debug configurations that all have to be set up properly to make things work. This is really more of an annoyance than a showstopper. But streamlining workflows can save a boatload of time when you’re under the gun to deploy apps to a deadline. I’d like to see these combined into a single window, much like the Project > Properties window.

Improve access to the latest ActionScript mobile documentation. I haven’t yet found Flex/ActionScript 4.5 documentation, and I’m still looking. What I mean is if I type “ActionScript 4.5” into a search engine I expected to find the documentation. I also would like to see all classes and packages that work with AIR 2.5.x mobile in one single location. You can’t even easily find officially labeled Flex 4 documentation on the web, and I did relay this information to Adobe on several occasions. At one point I came across this page listed as documentation. What I did find was typically for ActionScript 3, AIR 2 (old!) and Flash Lite 4. And since that was old documentation, it wasn’t clear what had changed.  I also looked on the Flash Builder Burrito labs site here and the Mobile and Devices Developer Center here which is the first place I would expect a link to be.  

All-in-all it looks like a Adobe did a great job so far. So, that’s it for now since I need to get back to playing with my prototype app. If you have any other likes or dislikes please let me know.

Random Hacks of Kindness #2 – Hacking for Humanity

This weekend I attended the Random Hacks of Kindess (RHoK) Conference in New York City. I even hacked a little and did a short presentation. It’s a conference for hackers who want to contribute free and open source software to help with humanitarian crisis response efforts around the world. The conference was held simultaneously at 21 global locations. The majority of the apps have some sort of mapping component. In attendance were hackers, project managers, fire chiefs and others from as far away as Sudan.

A variety of projects were worked on at the conference including  a mobile Incident Command app for responding fire agencies, hospital status monitoring app, and a Vulnerability Analysis and Mapping tool for the United Nations World Food Program. For a full list of problem definitions go here.

My project is a Twitter Search widget built for use with the open source ArcGIS Viewer for Flex. It monitors and maps Tweets for a geographic region, returning all Tweets within a specified radius. The ArcGIS Viewer for Flex is a mapping and visualization tool and it lets you integrate and display real-time data from multiple sources. In other words, you can use this tool to map Tweets alongside things such as earthquake data (GeoRSS), weather data (REST) and anything else with a geographic attribute, all in real time. Decision makers for emergency response agencies can use this visual fusion of real time information to help paint an operational picture, identify problems and see trends.

Many people opt-in for sharing their location information when they Tweet. If they have opted-in, the widget retrieves this information through Twitter’s Search API. You can see a live version here.  I originally built the widget for RHoK #0, right before the Haiti earthquake. This widget was used in the Haiti earthquake and the Tennessee flood. It has also been adopted by a variety of emergency response agencies that are using it today.

If you want to contribute to one of these humanitarian projects, check out the RHoK website for more information: http://www.rhok.org/

Resources:

Migrating from SQL Server 2005 to SQL Server 2008

Basically, I needed to migrate a fairly simple database from SQL Server 2005 to SQL Server 2008 for a project I’m working on. The database has six tables, dozens of columns, properties and unique keys. There was also a stored procedure and a trigger just to spice things up.

I was quite happy with how easy and fast the migration went. I’ve had seemingly simple database tasks go sideways before and take hours to resolve. From beginning to end, this whole operation took about five minutes.

Here are the steps I used, although yours may vary slightly.

  1. Launch SQL Server Management Studio on your SQL Server 2005 machine
  2. Right click on the actual database then click Tasks > Detach. This step insures there are no active processes accessing the database.
  3. Since my SQL Server 2008 database was locked down, I copied the .mdf and .log files from the SQL Server 2005 machine over to the corresponding directory on the SQL Server 2008 machine via Remote Desktop. SQL Server does have an option to copy from one database directly into another. However, that involves opening ports in firewalls to allow access between the server, and I didn’t have that luxury for security reasons. 
  4. Note 1:  Make double sure you don’t overwrite an active database of the same name on the destination server!

    Note 2:  the default installation directory for these files on SQL Server 2008 is here: C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA

  5. Launch SQL Server Management Studio on your SQL Server 2008 machine.
  6. Right click on “Databases” then select “Attach”.
  7. This will launch the Attach Databases window. Select “Add” and navigate to the correct .mdf file that you just copied over.
  8. Follow any additional prompts.  I didn’t have any full-text catalogs so I just clicked “OK” when that pop-up window appeared.  For me , SQL Server 2008 automatically converted the old SQL Server 2005 database into SQL Server 2008.

If you follow these steps, and if there were no errors, you are almost done. Before you pop champagne and celebrate make sure you can access the database from SQL Server Management Studio. Open the tables and run a quick test query just to make sure. If you have a more complex database you might want to run multiple test queries, and run your application, just to make sure everything moved over properly.  If you have a migration story please share it here.

IE 8 Developer Tools – A great step in the right direction.

Even though IE 8 Developer Tools have been around for a while, since Internet Explorer 8 Beta 1 (circa 2008), there are still a lot of developers out there who aren’t familiar with it. And, it’s well worth the time learning about it. Some of you may be wondering who develops against IE? Well, before I dive into the details, I wanted to say a word about that. According to w3schools as of October 2010, IE represents 29% of all browsers, and IE 8 browsers make up more than half of that number.

You should research your own website stats, and companies such as w3counter provide developer tools for that. In general, it’s fair to say that most consumer sites get a lot of IE-based traffic, and testing your app against IE is a good idea. If you don’t, there’s a strong chance you’ll frustrate a bunch of potential users and they may not come back, ever. If you run an internal site for an organization then you may have more control over which browsers (and browser versions) are used, and your life is probably easier than the rest of us.

I know I personally didn’t like testing against IE because with IE 6 and 7 the tools were pretty much non-existent and extremely unfriendly to web developers. I have to say that IE 8 made a huge step forward in my eyes when they included Developer Tools. Sure I have plenty of gripes, but all-in-all my job got much easier. Instead of blindly making changes and then reloading the page to see the results, I now do the majority of my testing and prototyping right in the Developer Tools.

Here just a few of the tools I find particularly useful:

  • Built-in Script debugger. Yep, it includes console, breakpoints, locals, watch and call stack.
  • Edit on-the-fly.
  • Inspect CSS.
  • Select element by click (Ctrl + B).
  • Clear cookies for domain
  • Tools > Resize (on-the-fly)
  • Show ruler.
  • Save HTML or CSS changes to a file.

I still have a wish list of things I’d like to see added, here’s my top five:

  1. Built-in HTTP transaction viewer. I mean they have Fiddler, why not bolt key pieces of it into the browser tools rather than having to launch Fiddler separately?
  2. DOM attribute inspector for those times when you have to dig deep; for example, when there are differences between content attributes and DOM attributes.
  3. Cookie Manager – including the ability to inspect/delete individual cookies.
  4. Automatically associate a selected element with its DOM index. Don’t make me have to hunt for it in a different view and then compare.
  5. Continuous hover and select item on page, without needing to click Ctrl + B every time. Sometimes I want to scan multiple items quickly.

So that’s it. This tool should save you a ton of time. Are there any items that are your favorites, and what do you want added to the wish list?