ActionScript.org Flash, Flex and ActionScript Resources - http://www.actionscript.org/resources
Dynamic Slide Show AS3 Complete Guide. Part 1: Loading Data
http://www.actionscript.org/resources/articles/892/1/Dynamic-Slide-Show-AS3-Complete-Guide-Part-1-Loading-Data/Page1.html
Jean André Mas
Graphic designer converted since 2004 to coding. I play around with C++, OpenGL, Java, Javascript, AND Actionscript.
My website: ASWC 
By Jean André Mas
Published on June 22, 2009
 
This is the first of a series of articles concerning the creation of a dynamic slide show using AS3 and OOP principles. Each article will explore a particular subject and introduce some common solutions, advice, tricks. Since every programming task can be solved in many ways, every reader is welcome to contribute to this series by adding his/her insights in a comment or by contacting me directly. Such insights might be added later in the series depending on their relevance. Each article also comes with files to download illustrating the article discussion. Each new article will build upon the preceding one. So let's begin this series with the first article about loading data.

Loading data (or why everybody uses XML?)

A Dynamic Slide Show is quite a simple application but the more dynamic you want it, the more complex it gets. This series of articles will show you how to create a dynamic, flexible, and versatile slide show with AS3. Each new article will be covering a particular subject in the creation of a Slide Show. The articles will be as follow:

1. Loading data (or why everybody uses XML?)
2. Loading Pictures (or How do I time this?)
3. Resizing and Auto resizing (or can the swf resizes itself?)
4. Adding Setup Options (or letting the user take charge)
5. Adding Effects and Create Custom Effects (or Put The BitmapData Class to Work)
6. Randomizing (or Adding Some Life)
7. Adding Texts (or The Advantage of Classes)
8. Adding Sound (or Turn That Off!)
9. Cleaning Up (or Learn How To Take The Trash Out)
10. CMS (or Live And Let Live)

Loading data (or why everybody uses XML?).

Most application must load some kind of data when they start and a Dynamic Slide Show is not different, it must load at least the path of the pictures it’s going to display and maybe additional information like timing, URL paths and so on. This first article shows you how to load data via an XML object.

Why everybody uses XML?

XML has become a standard on the web for passing information from Website to Website, from web application to server side and reverse, and in many other cases. The reason is simple, with XML the data is (or is supposed to be) well organized, already sorted for you. XML nodes are supposed to describe the data they enclose making the work of the programmer easier.

So let’s start building our slide show, create a new Actionscript 3 document, set its width and height to 400, its frame rate to 30 and save. Now let’s create our document class, create a new Actionscript file and save it in the same folder than the Fla file you just created, give it for example a name of “LoadingData.as”. Now back to our Fla file, set the document class as “LoadingData” and save. From now we will be working with the document class only but leave the Fla open anyway as we will need it for compiling the swf. Let’s create a simple XML that we will load in our application:

<SLIDE_SHOW>

<PICTURES>

<PICTURE_PATH></PICTURE_PATH>

<PICTURE_PATH></PICTURE_PATH>

<PICTURE_PATH></PICTURE_PATH>

<PICTURE_PATH></PICTURE_PATH>

</PICTURES>

</SLIDE_SHOW>

SLIDE_SHOW is what we call a root tag, it encloses all the other tags and is required to form a valid XML object. PICTURES is the tag that we will use to pass our picture paths to the application, this tag will enclose all the picture paths. PICTURE_PATH is our final tag and we will add paths inside these tags to point to our pictures. We still did not setup a picture folder but let’s go ahead and pretend we did and add some paths into our XML:

<SLIDE_SHOW>

<PICTURES>

<PICTURE_PATH>mypicture1.jpg</PICTURE_PATH>

<PICTURE_PATH>mypicture2.jpg</PICTURE_PATH>

<PICTURE_PATH>mypicture3.jpg</PICTURE_PATH>

<PICTURE_PATH>mypicture4.jpg</PICTURE_PATH>

</PICTURES>

</SLIDE_SHOW>

Here now there’s something in our tags, let’s save this XML as “slide_show.xml” and save it in the same folder as our Fla and as files.

Now let’s write our document class. Open the actionscript file named “LoadingData.as”. A document class in AS3 must be enclosed in a package so let’s do that first:

[as]package{ }[/as]

Quite easy, now inside this package let’s declare our document class (its name must match the actionscript file name):

[as]package { public class LoadingData { } }[/as]

A document class in AS3 must extend either MovieClip or Sprite, use MovieClip when you intend to use timeline-based animation, use Sprite when you won’t use any timeline. We won’t use any timeline-based animation here so let’s go ahead and extend Sprite. We import the Sprite class and extend it:

[as]package { import flash.display.Sprite; public class LoadingData extends Sprite { } }[/as]

Finally let’s create our constructor. A constructor is a function with the same name as the class, it never returns a value and will automatically run when the document class is called (when the application starts):

[as]package { import flash.display.Sprite; public class LoadingData extends Sprite { public function LoadingData() { } } }[/as]

I will not describe again how to create a document class in the next sections so if you forget how to do this, come back to this page and review the process.


Loading data (or why everybody uses XML?) part 2

Now time to write code that actually does something! Loading our XML! We need to import a couple of classes to load our data, the URLRequest class, all the events class package (we’ll need those) events.*, the TextField class that we’ll use to show our XML, and the URLLoader class. We also declare a few member variables: A variable to hold our XML data “var picture_xml:XML;”, a variable to hold our URLRequest “var url_request:URLRequest;”, and a variable to hold our URLLoader “var url_loader:URLLoader;”:

[as]package { import flash.display.Sprite; import flash.net.URLRequest; import flash.net.URLLoader; public class LoadingData extends Sprite { var picture_xml:XML var url_request:URLRequest; var url_loader:URLLoader; public function LoadingData() { } } } [/as]

Now in our constructor we are going to instantiate our URLRequest, and URLLoader variables, write some code to initiate the loading and add a COMPLETE event to trigger a function when the XML data is fully loaded:

[as]package { import flash.display.Sprite; import flash.net.URLRequest; import flash.net.URLLoader; import flash.events.*; import flash.text.TextField; public class LoadingData extends Sprite { var picture_xml:XML var url_request:URLRequest; var url_loader:URLLoader; public function LoadingData() { url_request = new URLRequest("slide_show.xml"); url_loader = new URLLoader(); url_loader.addEventListener(Event.COMPLETE, completeHandler); url_loader.load(url_request); } private function completeHandler(e:Event):void{ picture_xml = new XML(url_loader.data); var txt:TextField = new TextField(); txt.width = stage.stageWidth; txt.height = stage.stageHeight; txt.wordWrap = true; txt.text = picture_xml; addChild(txt); } } }[/as]

If everything went well you should like me see our XML displayed in our textfield. Now to be truly dynamic our slide show should be able to load different XMLs. For example you should be able to display two slide shows in the same html page with different pictures which means loading different XMLs. We can do so by using FlashVars.


Loading data (or why everybody uses XML?) part 3

Back to our Fla file you can go ahead and hit “publish” to get an html file with the slide show embedded. Now we can modify this html and add FlashVars to pass to our slide show. Open the html file in your favorite html editor or notepad and look for this:

[php]<script language="JavaScript" type="text/javascript"> AC_FL_RunContent( 'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0', 'width', '400', 'height', '400', 'src', 'loading', 'quality', 'high', 'pluginspage', 'http://www.adobe.com/go/getflashplayer', 'align', 'middle', 'play', 'true', 'loop', 'true', 'scale', 'showall', 'wmode', 'window', 'devicefont', 'false', 'id', 'loading', 'bgcolor', '#ffffff', 'name', 'loading', 'menu', 'true', 'allowFullScreen', 'false', 'allowScriptAccess','sameDomain', 'movie', 'loading', 'salign', '' ); //end AC code[/php]

add between two lines this ‘FlashVars’, ‘xml=slide_show.xml’, so you should now have this:

[php]<script language="JavaScript" type="text/javascript"> AC_FL_RunContent( 'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0', 'width', '400', 'height', '400', 'src', 'loading', 'quality', 'high', 'pluginspage', 'http://www.adobe.com/go/getflashplayer', 'align', 'middle', 'play', 'true', 'loop', 'true', 'scale', 'showall', 'wmode', 'window', 'devicefont', 'false', 'id', 'loading', 'bgcolor', '#ffffff', 'name', 'loading', 'menu', 'true', 'allowFullScreen', 'false', 'allowScriptAccess','sameDomain', 'FlashVars', 'xml=slide_show.xml', 'movie', 'loading', 'salign', '' ); //end AC code[/php]

Now look for this:

[php]<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0" width="400" height="400" id="loading" align="middle"> <param name="allowScriptAccess" value="sameDomain" /> <param name="allowFullScreen" value="false" /> <param name="movie" value="loading.swf" /><param name="quality" value="high" /><param name="bgcolor" value="#ffffff" /> <embed src="loading.swf" quality="high" bgcolor="#ffffff" width="400" height="400"name="loading" align="middle" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer" /> </object>[/php]

and add FlashVars at two places like this:

[php] <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0" width="400" height="400" id="loading" align="middle"> <param name="allowScriptAccess" value="sameDomain" /> <param name="allowFullScreen" value="false" /> <param name="FlashVars" value="xml=slide_show.xml"> <param name="movie" value="loading.swf" /><param name="quality" value="high" /><param name="bgcolor" value="#ffffff" /> <embed src="loading.swf" quality="high" bgcolor="#ffffff" width="400" height="400" FlashVars=”xml=slide_show.xml” name=”loading” align=”middle” allowScriptAccess=”sameDomain” allowFullScreen=”false” type=”application/x-shockwave-flash” pluginspage=”http://www.adobe.com/go/getflashplayer” /> </object>[/php]

Now let’s modify our document class to load our FlashVars prior to load our XML, we do this in the constructor:

[as]var xml_path:String = ""; xml_path = this.loaderInfo.parameters.xml || "slide_show.xml"; url_request = new URLRequest(xml_path);[/as]

Now if you compile the application and run it in a browser you should be able to see our xml data and you should be able to pass different XMLs too. A little explanation about his line:

[as]xml_path = this.loaderInfo.parameters.xml || "slide_show.xml";[/as]

This is a conditional that will allow us to keep developing our application in Flash CS3/4 since FlashVars is available only in a browser. The conditional first passes the FlashVars to the string variable and if the value is not available it then passes the string path which is the one we’ll use for developing. Now let’s go even further and load instead of an XML file, an XML object.


Loading data (or why everybody uses XML?) part 4

An XML object is not an XML file, an XML object is any valid XML formatted document or string that can be interpreted as XML. So another way to load XML data is to use a server side script like this PHP one called “simple.php”:

<?
$xml = "<SLIDE_SHOW><PICTURES><PICTURE_PATH>mypicture1.jpg</PICTURE_PATH><PICTURE_PATH>mypicture2.jpg</PICTURE_PATH>";
$xml .= "<PICTURE_PATH>mypicture3.jpg</PICTURE_PATH><PICTURE_PATH>mypicture4.jpg</PICTURE_PATH></PICTURES></SLIDE_SHOW>";
print($xml);
?>

Now we can modify the FlashVars to pass this “simple.php” instead of an XML file. Let’s do that and upload everything to a PHP enabled server and test it. If everything went well you should like me see our data. Now let’s go further in the server side script interaction, we could use our server side script to look inside a folder and pass as an XML object any picture we find, so let’s set up a folder with a few pictures on the server and create a new PHP script to grab any pictures it can find, this script is called “external.php” don’t forget to change the FlashVars when testing this:

<?php
$dir = opendir("assets/");
print("<SLIDE_SHOW><PICTURES>");
while($file = readdir($dir)){
if((substr(strtolower($file),-4)==".png") || (substr(strtolower($file),-4)==".jpg") || (substr(strtolower($file),-4)==".gif") ||
(substr(strtolower($file),-5)==".jpeg")){
print("<PICTURE_PATH>assets/".$file."</PICTURE_PATH>");
}
}
print("</PICTURES></SLIDE_SHOW>");
?>

When you test this you get back an XMLobject with all pictures present in a given folder. We can also apply the same principle with a database, we could create a database to save the picture paths and give each picture a type so our php script will give us the right pictures for the right slide show. For example if there’s a slide show on an index page then we could have pictures in the database with the type “index” and for another slide show on the about page we could have type ‘about’. Let’s see this in action with this new PHP script called “database.php” and let’s pass the picture type directly as a query with the PHP script name like this:

xml=database.php?type=index

and here is the script:

<?php
$db = mysql_connect("yourid", "yourusername" , "yourpassword");
mysql_select_db("yourdatabase",$db);
$query = 'select PICTURE_PATH from PICTURES where TYPE='.$_REQUEST['type'].’ ‘;
$query_result = mysql_query($query);
print(”<SLIDE_SHOW><PICTURES>”);
while ($row = mysql_fetch_array($query_result, MYSQL_ASSOC)) {
print(”<PICTURE_PATH>”.$row['PICTURE_PATH'].”</PICTURE_PATH>”);
}
print(”</PICTURES></SLIDE_SHOW>”);
?>

As you saw loading data is a bigger subject than one might think, anyway we covered the most standard situations with the database loading being the most flexible in my opinion since we’ll be able to link this easily to a CMS (sure why not?). Now it’s time to laod some pictures!