Welcome!

Adobe Flex Authors: Keith Swenson, Jacques Durand, Pat Romanski, Liz McMillan, Aditya Banerjee

Related Topics: Adobe Flex, XML

Adobe Flex: Article

XML, Another Way to Run Your Flash Application

XML, Another Way to Run Your Flash Application

What does data look like? To a stockbroker, data might appear as a stream of company names and stock values. A database administrator probably sees data as a series of tables. A developer working in XML might see data as a tree like structure.

This article is all about data. We will look at data, data structures, data transformations, and data bindings and examine their role in the Flash MX 2004 component framework. We'll use this information to build our first RAD App in Flash, an XML-driven data consumer.

Variables are the most basic abstraction of data (see Figure 1). Some symbol is assigned to represent some value. Just like in a stock ticker, a name is associated with a value. This works great for simple things such as stocks, names or ids, but is not very useful when dealing with more complex data models. Variables are not a good tool to organize the multiple pieces of information that are needed to represent a student, an employee, or a product.

Object-based data modeling employs the concept of special variables, called objects, which are able to hold multiple values called properties (see Figure 2). (Objects also have specific functionality associated with them, things that they can do, called methods. This discussion is limited to object properties.) Properties are like a variable inside a variable. With properties, a single variable can hold all of the values we need to represent something from the real world. A student object can have names, ids, courses, and grades. Products can have names, ids, descriptions, suppliers, prices, etc. Properties provide an intuitive way of accessing data by simply using object and property names. One variable can encapsulate all of the values needed to define a specific item. Now, how do we handle working with many items?

Arrays provide a handy storage container when we're working with many related things. Arrays are nothing more than special variables that allow us to store multiple values at different positions, indexed by number. This allows us to gather like things together into one easily manipulated collection. Arrays (see Figure 3) are the filing cabinets and shopping carts of the developer's world.

Objects are the things we need to collect and store. Arrays are where we store things. Put the two together and we get: arrays of objects. While there are many other data structures out there, arrays of objects are a key building block for data- driven applications in Flash. Data from SQL queries and XML structures will appear as arrays of objects in Flash (see Figure 4).

The ComboBox, List, and DataGrid components all use arrays of objects as their data providers. While the DataGrid is happy using any array of objects as a data provider, the List and the ComboBox can take advantage of special data providers, which use an array of specially formatted objects. List and ComboBox components like data providers where the array's objects have only two properties; label and data (see Figure 5).

The objects returned in arrays from SQL queries and XML structures can be rearranged into objects having label and data properties.

Programmatically, this is done by looping over the source array and using the properties of the source array's objects to create a new array. Properties of the source array's objects are used to build the special objects that have label and data properties.

While this transformation of objects is not very difficult, Flash's component framework makes it even simpler. The component binding interface provides a simple formatter that rearranges the properties of a source array's objects into data provider objects with label and data properties. This is the process shown in Figure 6. We will use this technique when we build our XML-based application.

XML provides a simple markup that describes data and its structure. It is very flexible, allowing developers to create their own data structures. The rules for forming the structures are contained in the document's schema. XML's flexibility makes it an important part of Web services and will be examined in a later article. XML has the additional advantage of being simple, uncompiled text. No special programs are needed to read or write XML documents and no special servers are required if the XML exists as text documents.

With XML, tabular data (see Figure 7) can be represented as a simple tree-like structure. As with HTML, line breaks and white space can be used to make the files more readable. While a visual examination of an XML document may clearly reveal the document's structure (see Figure 8), navigating that XML structure in Flash is slightly less than intuitive.

Navigating XML structures programmatically in Flash requires the use of hierarchical syntax. While the syntax is not overly difficult it lacks the intuitiveness of working with the numbered elements of an array and the named values of an object's properties. Even examining XML in Flash's debugger can be awkward.

Flash simplifies things for developers by making XML appear as an array of objects in the component interfaces (see Figure 9). The XML connector's results displays XML's characteristic structure, but the same XML in the bindings or schema tabs of the component inspector appears as an array of objects (see Figure 10). Visualizing the data this way makes working with XML much more intuitive.

Putting It Into Practice
Let's put all this into practice and build our XML-driven Flash application. We will load XML representing a catalog of products into Flash, build a master-detail view, and do a little custom formatting and coding.

Remember, all component-based data integration in Flash follows the same basic steps:

  1. Add a data connector
  2. Provide connection information
  3. Add UI components
  4. Bind UI components to data and each other
  5. Trigger the data connector
We'll start with a new Flash document. (We're supposed to call them Flash documents these days, but they'll always be Flash movies to me.) Save the document into a directory that has the data source, products.xml in it.

Step 1
Add an XMLConnector from the components panel to the document. The XMLConnector does not render, it is invisible in the final application. It is usually placed just off of the stage. Give the XMLConnector an instance name of cxn (see Figure 11). Next we provide the connection information.

Step 2
With the XMLConnector selected on stage, go to the Parameters tab of the Component Inspector. Set the URL to products.xml, and direction to receive. Leave the other parameters at their defaults. It is especially important to leave ignoreWhite set to true. This prevents Flash from trying to interpret spaces in the XML as data (see Figure 12). Move over to the Schema tab of the Component Inspector. Here, we provide the connector with a sample of our XML. From that sample, Flash will figure out the document's schema, the structure of the data. This will allow us to bind UI components to the XML data by the properties names. First be sure you select the results property, not the param property. Then, use the Import schema button to open products.xml. Notice that the XML is displayed as an array of objects after importing (see Figure 13).

Step 3
For the UI components we will use a List component and two Label components. We will give the List an instance name of myList and the two Labels instance names of price_lbl and description_lbl. We are ready to bind the results of the XML connector to our List.

Step 4
Select the XMLConnector on the stage and move to the Bindings tab of the Component Inspector. Click the plus sign ( + ) to add a new binding. Select the product : Array in the Add Binding window, then click OK. Back in the bindings tab, move down to the bound to field and bind to the myList List component as a DataProvider array. The final binding will look like Figure 14.

Step 5
We want our data to load as soon as our application opens. The best way to do this is with some actionScript in the first frame of our application. Add an actions layer and select frame 1. We will use a behavior to trigger our data connector. Flash behaviors, like Dreamweaver behaviors, are code snippets that have been prebuilt for us. Move to the Behavior Inspector and click the plus sign ( + ) to add a new behavior. Choose Data > Trigger Data Source and then select the XMLConnector: cxn (see Figure 15). Our application is ready for the first test.

Test the application; compile and open the SWF. If all has gone well, the list is populated with data. If the list isn't populated, go back over the steps. Be sure the XML and SWF are in the same directory, check names, bindings, etc. Sometimes it is quicker and easier to just start over again and rebuild the application from the beginning.

If the list populated, you may be surprised at the results. Each list item shows all of the properties for that object in a single comma-separated line. To control how the results are displayed in the List, we need to change how the results are bound to the List's data provider. We need to transform properties of the XMLConnector's results into label and data properties in the data provider for the list. Flash provides a simple way to accomplish that transformation.

With the XMLConnector selected, in the Bindings tab of the Component Inspector select the results.catalog.product binding. From the formatter field choose Rearrange Fields. The Rearrange Fields formatter provides an easy way to use simple statements to perform data transformations.

Enter label=name;data=. into the formatter options exactly as written, with no extra spaces. Now, let's pick that statement apart.

The label=name assignment says: take the name property from the source object and assign it to the label property of the data provider object. The semicolon is used to separate assignments. The data=. assignment says: take all of the properties of the source objects and assign them to the data property of the data provider objects. The period ( . ) represents all of the current data or all of the data at this point. The data property of the data provider objects now holds all the properties of the source object.

By using rearrange fields we have created a useful data provider for our List. The label property of the data provider objects will automatically show up as labels in our list. The data properties of the data provider objects hold all of the original data for that object. In this example the object represents our XML values. In future examples, the data provider's data property will be a record from a database and the data properties will be the fields from a record.

XML and Flash
This concept of labels and data is a step ahead of normal form objects in HTML. Normal HTML form objects have labels and values. HTML drop-down boxes and list objects show a label to the user that represents some simple value. With Flash components the label can represent complex data. In a Flash List, the data provider object's label property is shown to the user. We can then access that item's data property to get any value we need for that object. This provides a simple means of creating data drill downs in master-detail views. Details can be easily retrieved from a selected item's data property. We will use this as we bind our remaining components.

We will bind the List component to the Labels. When the user selects a list item they will see details about the selected item in the Labels. I like to work with data in Flash in the direction it is traveling. When we connected the XMLConnector to the List we started by selecting the XMLConnector. To bind the List to our Labels we start by selecting the List.

With the List selected, go to the Bindings tab of the Component Inspector. The binding from the XMLConnector is already listed. Click the plus sign ( + ) to add another binding. The Add Binding window opens with a number of different choices. Remember, we need to bind to a property of the selected item's data. The Add Binding window provides a binding to selectedItem : Object but it does not expose the selected object's data property. The Use path expression check box provides a way to bind to data that is not exposed in the list.

Check the Use path expression check box at the bottom of the Add Binding window. In the field below it enter data.price (see Figure 16). This creates a binding to the price property of the selected object's data property. Click the OK button to close the Add Binding window.

Use the bound to field of the component inspector to complete the binding. Select price_lbl as text : String to be the end point of this binding.

Click the plus sign ( + ) and repeat the binding process. Add a new binding from the selected object's data.description property (Remember to turn on Use path expression.) bound to description_lbl's text : String.

During testing, clicking on an item in the List now reveals details in our Labels. We have a basic model for data drill down interfaces but there are two small issues.

When the data loads into the list it is not sorted; it comes in ordered the way it is written to the XML. It may be useful to sort the List alphabetically for the user. The other issue is that it would be nice to put a $ in front of the price in the Label. We'll take care of that first by using a new formatter; Compose string.

Select the List on stage and go to the Bindings tab of the Component Inspector. Choose the selectedItem.data.price binding from the list. Below, in the formatter's field, select the Compose string formatter. From the formatter options field open the Compose String window. The String template field will let us mix literals such as the $ sign with data. Literals are put in the String template field without markup. Data must be enclosed in < >.

Enter $<.> in the String template field. The $ sign is literal and <.> says use the data at this point. The data at this point in the binding is the price. Close the Compose String window and our price formatting is finished. Now to sort the List.

Sorting the List takes just a little bit of code, which can be put into many places in a Flash movie. There are many good reasons to keep all of a project's code in one place such as frame 1 or external files. However, placing code directly on an object provides a very direct method and allows for the use of a simpler syntax for the event handlers. To sort the list we will use this simpler, more rapid method of placing the code directly on an object. The XMLConnector will be the object we place the code on.

Select the XMLConnector on stage, open the actions window, and enter the following code:


on(result)
{
  this._parent.myList.sortItemsBy("label", "ASC")
}

This code says: when we get results from our call for XML, sort myList using the label property.

That finishes the application for this article. In upcoming articles we will build applications using information returned from a database via Web services and Flash Remoting.

Summary
In my next article we will build the data sources we will use in those future applications. Even though data can be supplied to Flash by many back ends, our data sources will be implemented using ColdFusion components (CFCs). CFCs provide a wonderfully simple way to create Web-based data sources. Next time I will show you how eight simple lines of code can create both a Web service and a Flash Remoting data source.

More Stories By Art Phillips

Arthur Phillips has been delivering cutting edge training solutions since 1984 and has developed instructional materials for George Washington University, the Federal Reserve Board, the U.S. Graduate School and many others. Art has an extensive background in video, multimedia, electronic graphics, Web development, and e-Learning. He holds too many certifications as a Macromedia Instructor, Designer, and Developer to list. His Web site (www.artswebsite.com) is a well-known resource in the Macromedia community.

Comments (3) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
Rich 09/11/05 11:44:55 PM EDT

Where the product.xml file?

Ian 02/10/05 06:50:41 PM EST

Where do I find the example products.xml file used in this article? I am a new subscriber and would like to go through this tutorial. Thanks

thiru 11/24/04 12:14:41 AM EST

I am flash programmer from india who is smart and dynamic, I am here to get smarter :).