Flex Tip: How to get all items (ignoring the filter) in an ArrayCollection

If you have an ArrayCollection with a filter function set and you loop through the items, you’ll only see the items which match the filter. The catch is sometimes you want to see them all. Initially I was doing the following.

var filterFunction:Function = arrayCollection.filterFunction;
arrayCollection.filterFunction = null;
arrayCollection.refresh();
			
for each (var obj:Object in arrayCollection)
{
	// do stuff
}
			
arrayCollection.filterFunction = filterFunction;
arrayCollection.refresh();

This worked but was pretty ugly. Here’s a nicer approach:

for each (var obj:Object in arrayCollection.source)
{
	// do stuff
}

What I keep finding in Flex is that I’m able to come up with complex code to solve simple problems but when I revisit it months later there’s usually a more straight-forward solution.

Hope this helps,
Hillel

Flex Tip: Convert XML to ArrayCollection

This is one of those things that took me much longer than I thought it would have. I needed to convert a file containing XML data to an ArrayCollection. My XML file looked like this:

<rows>
	<row>
		<col1>some value</col1>
		<col2>another value</col2>
		...
	</row>
	...
</rows>

I wanted to convert this into an ArrayCollection with each row as an object (and I didn’t want to have to loop through each item in the list). Here’s the solution I’m using.

import mx.utils.ArrayUtil;
import mx.rpc.xml.SimpleXMLDecoder;
import mx.collections.ArrayCollection;
			
private function convertXmlToArrayCollection( file:String ):ArrayCollection
{
	var xml:XMLDocument = new XMLDocument( file );
			
	var decoder:SimpleXMLDecoder = new SimpleXMLDecoder();
	var data:Object = decoder.decodeXML( xml );
	var array:Array = ArrayUtil.toArray( data.rows.row );

	return new ArrayCollection( array );
}

I’m not thrilled with this approach because I’ve needed to hard code the XML structure (’rows.row’) into the function. If anyone has a better solution I’d love to see it.

Best,
Hillel