25Jun

Image Gallery - Part IV - XML File Loading

4 comments so far

So far we have our image gallery, now I want to put all the image location url’s within an xml file for ease of use. The limitation here is that I originally just have 2 categories and the function that controls the toggle to each category has to have the same name as the page node id name. For instance, the function categoryOne in Main.as calls a function ParseArray with a parameter of Category1 - this corresponds to the id attribute of teh page node within our xml file. The issue is that I would ideally like to add more page nodes to the xml file and have the flash movie update as well. Unfortunately not enough time to expand on this, so I will leave it as is.. although I am totally up for an alternative suggestion.

So, because I can never parse xml files within my blog properly, here is a link:

http://manewc.com/projects/flash/xml/images.xml

I just updated the Main Document class file to load in my xml file:

package
{
	import flash.display.Sprite;
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.events.Event;
	import flash.events.KeyboardEvent;

	public class Main extends Sprite
	{
		private var GalleryImagesArr:Array;
		private var CatGallery:ImageGallery;
		private var theater:Sprite;
		private var myXMLFile:LoadXML;
		private var ct:Number = 0;
		private var c:Number = 0;
		private var imgCategory:XMLList;
        private var imgThumbnail:XMLList;
        private var imgLarge:XMLList;
		private var xmlImages:Array;
		private var categoryArr:Array;
		private var myHook:Array;

		public function Main()
		{
			theater = new Sprite();
			addChild ( theater );

			LoadXMLFile();
		}

		private function LoadXMLFile():void
		{
			myXMLFile = new LoadXML ( "http://manewc.com/projects/flash/xml/images.xml" );
			addChild ( myXMLFile );

			// setup the listener for detecting when xml file is loaded
			myXMLFile.addEventListener ( Event.ENTER_FRAME, LoadXMLCheck );
		}

		private function LoadXMLCheck( e:Event ):void
		{
			if ( e.currentTarget.LoadComplete() )
			{
				// XML FILE LOADED - clean up
				e.currentTarget.removeEventListener ( Event.ENTER_FRAME, LoadXMLCheck );

				// let's parse the xml
				ParseXML ( e.currentTarget.GetXML() );
			}
		}

		private function ParseXML ( xml:XML ):void
		{
			// Gather the attribute data
			var imgCategory:XMLList =  myXMLFile.xml.page.@id;
            var imgThumbnail:XMLList = myXMLFile.xml.page.image.@thumbnail;
            var imgLarge:XMLList =  myXMLFile.xml.page.image.@large;  

  			xmlImages = new Array();
			categoryArr = new Array();

            for each (var thePage:XML in imgCategory)
            {
				categoryArr.push ( imgCategory[ct] );

				for each ( var theImage:XML in xml.page[ct].image )
				{
					xmlImages[c] = new Array ( imgThumbnail[c],imgLarge[c],imgCategory[ct] );

					c++;
				}

                ct++;
            }

			initStage()
		}

		private function ParseArray ( hook:String )
		{
			if ( GalleryImagesArr ) GalleryImagesArr.splice();

			GalleryImagesArr = new Array();

			for ( var d:uint = 0; d < xmlImages.length; d++ )
			{
				if ( xmlImages[d][2] == hook )
				{
					GalleryImagesArr.push ( new Array(xmlImages[d][0],xmlImages[d][1]) );
				}
			}

			return GalleryImagesArr;
		}

		private function initStage():void
		{
			// set the stage
			categoryTwo();

			// set the listener
			stage.addEventListener ( KeyboardEvent.KEY_DOWN, changeCategory );
		}

		private function categoryOne():void
		{
			myHook = ParseArray("Category1");

			CatGallery = new ImageGallery ( myHook );
			theater.addChild ( CatGallery );
		}

		private function categoryTwo():void
		{
			myHook = ParseArray("Category2");

			CatGallery = new ImageGallery ( myHook );
			theater.addChild ( CatGallery );
		}

		private function changeCategory ( k:KeyboardEvent ):void
		{
			if ( k.keyCode == 49 )
			{
				cleanChildren();
				categoryOne();
			}
			else if ( k.keyCode == 50 )
			{
				cleanChildren();
				categoryTwo();
			}
		}

		private var theaterArr:Array;
		private var childrenArr:Array;

		private function cleanChildren()
		{
			// get children
			theaterArr = traceChildren ( theater );

			// find children, if exist then delete
			for ( var t:uint = 0; t < theaterArr.length; t++ )
			{
				if ( theaterArr[t] == "[object ImageGallery]" )
				{
					theater.removeChild( theaterArr[t] );
					theaterArr[t] = null;
				}
			}
		}

		private function traceChildren(d:Sprite)
        {
			childrenArr = new Array();

            for ( var k:uint; k < d.numChildren; k++ )
            {
                var o:DisplayObject = d.getChildAt(k);  

                if ( o is DisplayObjectContainer )
                {
                    childrenArr.push ( o );
                }
                else
                {
					// childrenArr.push ( "" );
                }
            }

			return childrenArr;

        }
	}
}

and a new class that I added to load in my xml file:

package
{
	import flash.display.Sprite;
    import flash.net.URLLoader;
    import flash.net.URLRequest;
	import flash.net.URLVariables;
    import flash.events.Event;
	import flash.events.ProgressEvent;
	import flash.events.IEventDispatcher;
	import flash.events.SecurityErrorEvent;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
    import flash.xml.XMLDocument;  

	public class LoadXML extends Sprite
	{

		public var loadStatus:Boolean=false;
		public var xml:XML;

		public function LoadXML(xmlurl:String):void {
			var loader:URLLoader = new URLLoader();
            configureListeners(loader);

            var request:URLRequest = new URLRequest(xmlurl);

            try {
                loader.load(request);
            } catch (error:Error) {
                trace ("Unable to load requested document.");
            }
		}

		private function configureListeners(dispatcher:IEventDispatcher):void {
            dispatcher.addEventListener(Event.COMPLETE, completeHandler);
            dispatcher.addEventListener(Event.OPEN, openHandler);
            dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler);
            dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
            dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
            dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
        }

		private function completeHandler(event:Event)
		{
			xml = new XML(event.target.data);
			loadStatus = true;
        }

		public function LoadComplete()
		{
			return loadStatus;
		}

		public function GetXML()
		{
			return xml;
		}

        private function openHandler(event:Event):void {
            trace ("XML openHandler: " + event);
        }

        private function progressHandler(event:ProgressEvent):void {
            trace ("XML progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal);
        }

        private function securityErrorHandler(event:SecurityErrorEvent):void {
            trace ("XML securityErrorHandler: " + event);
        }

        private function httpStatusHandler(event:HTTPStatusEvent):void {
            trace ("XML httpStatusHandler: " + event);
        }

        private function ioErrorHandler(event:IOErrorEvent):void {
            trace ("XML ioErrorHandler: " + event);
        }
	}
}

Share/Save/Bookmark

Wednesday, June 25th, 2008 at 10:08 am and is filed under Actionscript 3, Actionscript XML, Image Gallery Project. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

4 Responses to “Image Gallery - Part IV - XML File Loading”

  1. Posted by Cassandra Cook 28th June, 2008 at 12:51 am

    Thank you for publishing your code. It helped me a lot.

  2. Posted by admin 30th June, 2008 at 11:16 am

    Glad it helped!

    Morgan

  3. Posted by Flash Tutorials | 18 AS3 Image Gallery Tutorials Roundup | Lemlinh.com 8th August, 2008 at 5:22 am

    [...] Image Gallery [...]

  4. Posted by Arte Fact 21st September, 2008 at 5:21 am

    Hello,
    Would it be possible to know how put all together?
    I mean fla, as files , how do they work together?

    It would be great!!!

    Thanks in advance

Leave a reply