Single Item ArrayCollections
I’ve seen a lot of people asking about this problem and I’ve seen various solutions. As it seems to be fairly common, I thought I’d share my solution too.
The Problem
The problem arises when you create an ArrayCollection from some data, and it only has one item. For some reason this is not classified as a collection (I guess by definition you need more than one of anything to make a collection) and therefore when you create your ArrayCollection to use as a DataProvider, it throws and error as it believes the ArrayCollection is null.
Consider the following block of code:
private function handleResult(e : ResultEvent):void
{
_myArrayCollection = e.result.item as ArrayCollection;
}
In this instance, if e.result.item is a single item the debugger will throw a TypeError.
The Solution
To overcome this, we simply need to check if indeed the data we’re trying to use to create our ArrayCollection involves multiple items. I’ve found the easiest and most failsafe way to do this is to check it against a type. For the sake of simplicity, let’s say the data source for the ArrayCollection is an Array of Strings. All we need to do is check if the the data is a String. If it is, then we know there’s only one item and we can create our ArrayCollection using the ArrayCollection(source:Array) constructor. If it isn’t a String, we can assume it is a group of items and can therefore cast them as an ArrayCollection.
private function handleResult(e : ResultEvent):void
{
_myArrayCollection = (e.result.item is String)
? new ArrayCollection([e.result.item])
: e.result.item as ArrayCollection;
}
Like I said, there are a few different ways of doing this so have a look around and see what works best for you.
