1. Code
  2. Flash

Build an XML Driven Contact List Using Flex 3

Read Time:10 minsLanguages:

The goal in this tutorial is to built a contact list which loads dynamically from an external XML file. When the user selects a different contact, the data will automatically update to display properly. We'll also be applying some basic stylesheet changes to the results and give the project a more customized touch.

Final Result Preview

Let's take a look at a screenshot of the final result we will be working towards:

Complete Contact ListComplete Contact ListComplete Contact List

Note: As you’ll quickly realize, I do not use the SDK to build Flex 3 files. While this tutorial is taught from the perspective of the Flex 3 Builder, the underlying code is the same. SDK users, you’ll simply have to substitute steps as needed. I won’t be using the design view in this tutorial, so you’re in luck.

Step 1 - Free for Education

Flex is a great development platform. It's better when you have the full Flex 3 Builder. Lucky for eligible students and faculty, Adobe is offering a full Education Flex 3 Builder license to you for free

Consider this a friendly reminder. If anyone with educational ties has yet to take advantage of the “Free Flex 3 for Education” deal yet, go ahead and do that now. It’ll help you out enormously.

Now that we're finished with the "free Adobe product" evangelism, let's build a Flex application!

Step 2 - Set Up Project Files

Start by creating a new Flex project for the web. Name it whatever you'd like, this step will not have an impact on the results.

Within the project, start a new MXML Application (File > New > MXML Application). Name the file "contactManager".

Layout SetupLayout SetupLayout Setup

For layout purposes, I recommend changing the layout default to "vertical". This will center all immediate child components on the page, which will work much better with our end goal.

Step 3 - Download Images

Each contact will display a profile picture when selected. For this example, we will be using Bill Gates and Barack Obama as contacts. Steve Jobs' press photo was just too terrible

Contact Profile PicturesContact Profile PicturesContact Profile Pictures

I've cropped their press photos (retrieved here and here) to smaller dimensions for this tutorial. Grab the edited versions here, and we'll move onto the XML file.

Step 4 - Introducing the XML File

All of the information displayed will be pulled from an external XML file. The basic structure is as follows:

As you can see, there are four main fields for each entry. The contact name, their position, email, and url to a profile image.

Download the file, and we'll be ready to arrange all of the files you've downloaded into asset folders for Flex.

Step 5 - Arrange Project File Structure

Make sure your project files are arranged as in the image below. You will need to make the folder "assets" for user-data.xml, and an "images" folder for the profile shots (File > New > Folder with "src" folder selected).

Import the files downloaded in step 4 and 5 into their corresponding folders. With the target folder selected, select File > Import > Other and use the prompt to select a file. Rinse and repeat for each until you've got all three in place.


Step 6 - Make Request for XML File

In Flex MXML, external files are most commonly loaded in with the HTTPService tag. Think of it like preparing an envelope to mail. It contains a target destination and includes instructions for what to do with the contents.

Create a HTTPService tag to request our XML file by entering the following tag immediately under the opening application tag.

This HTTPService has an ID of "userData" and loads our user-data xml file. The resulting data is formatted as E4X and passed to the contentHandler function we will be making shortly for processing.

Take note however, because simply making a HTTPService tag does not send the request. Just like an envelope needs a mailbox to travel, the HTTPService request must be actually sent.

Step 7 - Send Request on CreationComplete

In order for this request to be sent, we must activate it once the project successfully loads. We do this using the creationComplete event in the application tag.

While we could just directly insert the userData.send() method here, we're going to use a more expandable function init() to send the request instead. This function will be responsible for actions fired once the Flex project loads, and opens up the possibility for multiple load events. We'll fill in the contents of this function during a later step.

Step 8 - Set Up for Actionscript

The actionscript of this project will be responsible for handling the loaded XML file, storing filters, and updating components as needed. This will be accomplished with three separate functions.

Remember that Flex is a framework for actionscript, much like jQuery is to JavaScript. This means that even though Flex tags are designed to streamline common actionscript usages, it can also handle direct scripting as well. For this, we'll need to designate an area for the scripting to go.

And this is where the Script tag comes into play. Insert the tag directly below the opening Application tag. This is where all actionscript will be written; kept separate from the MXML below. If you're in the Builder, the tag will automatically add the CDATA markup:

We'll start by importing the ResultEvent package that is required for the HTTPService tag. (Remember that all the code in this section goes between the script tags mentioned above)

Step 9 - Declare Variables

In order to build XML filters, we'll need to define some variables. Both with be defined as bindable, which allows us to directly link the contents to a Flex component (e.g. Label).

The userList XML List will contain the E4X formatted results from the loaded XML file. We will use it to populate the data grid component in a later step.

The selectedData XML variable will hold the currently selected result in the data grid component. It will be responsible for populating the information fields and profile image.

Step 10 - Build the init Function

The init() function that we referenced in the last step will do two things.

  1. Send the request for the user data XML file.
  2. Set the name label (yet to be created) to a default "No Contact Selected" text

The code below will accomplish both. Ignore any warnings about nonexistent components for now, we'll be creating the referenced label in the next step.

Step 11 - Build the contentHandler Function

The next function is the contentHandler called by the result event of the HTTPService tag. This function takes the passed event, and then assigns the userList XML List variable the resulting XML data as filtered to the "user" level.

Step 12 - Build the showProfile Function

The last function (showProfile) is activated when a name is selected from the contact list. It simply assigns the contents of the currently selected XML entry to the variable selectedData. This is the variable that will be bound to the labels and image containers for live updates.

Now that the actionscript is in place, we're ready to put together the design.

Step 13 - Block out the Layout

The contact list layout will consist of a series of HBox and VBox containers (horizontal and vertical respectively). The block out below illustrates the structure of the final design.

Block LayoutBlock LayoutBlock Layout

Step 14 - Create Layout Components

All of this content we've loaded in will need a home. That's where the layout's components come in. Paste in the following structure below the HTTPService tag.

MXML has a nice advantage of being relatively simple to read. The only component that may be throwing someone new to Flex off is the Data Grid. Essentially the data grid is a table. The columns tag between the DataGrid tag specify the header text and fields for individual columns.

These are the components that will be used to load data from the XML file. In the next step, we'll populate each with the relevant data.

Step 15 - Populate the Components

Patching in the data from the XML entries is surprisingly simple. Copy in the following code changes, and meet back below for a summary.

Here's a breakdown of what's going on:

  1. The data grid is populated by binding the userList XML list to it. The column loads the data field "name" from each entry.
  2. When the selected item on the data grid changes, it calls the showProfile function to update the selectedData XML.
  3. The labels are each set to display a field of the selected entry.
  4. In the right column, the image containers source is loaded from the url in the XML file.

Step 16 - Change the Background Colors

If you work with Flex for a while, it's easy to become sick of the default color scheme. Let's make some quick fixes to spice things up.

We'll start by changing the background to a gradient in blacks. Update your opening application tag to include the gradient properties below:

The downside of a black background is that none of the default text will be visible. We'll fix this by using Flex's CSS to change font colors.

Step 17 - Style the Results

Did you know that Flash and Flex support their own brand of CSS? We'll be using some basic formatting to improve the readability of this application. Start by inserting a style tag directly below the opening Application tag.

The CSS offered in Flex is limited, but we can still make effective visual changes. In the CSS below, I've changed all the labels to a white font for readability. The HBox containing everything has been given a black background and padding of 20px on each side for spacing.

*Note that you must capitalize the component names in the CSS in order for it to reference properly.

Step 18 - Source Code for Project

If you haven't fallen in love with Flex yet, this next feature may push you over the edge. Flex makes sharing a project's source code not only easy, but really good looking. Take a look at the results, in a surprisingly browser-friendly design.

Step 19 - Conclusion & Further Applications

What you should have now is a XML driven contact list in Flex. Give it a test run and make sure everything is in working order.

Flex, as the name implies, is incredibly flexible. This means that you can take the framework from the tutorial above, and continue to add on. The data grid component will expand as needed.

Flex has a large variety of transitional effects, such as blur and resize, that can be applied on each change. The results of this tutorial could be a great place to start experimenting with more visual options such as these.

Go ahead and experiment! If you come up with any cool additions, be sure to share them with us in the comments.

Complete Contact ListComplete Contact ListComplete Contact List
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.