Build an XML Driven Contact List Using Flex 3

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 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 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 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:

<userlist>
	<user>
		<name>Bill Gates</name>
		<position>Head Nerd</position>
		<email>bill@microsoft.com</email>
		<image>images/gates.jpg</image>
	</user>
</userlist>

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.

Directory

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.

		<mx:HTTPService url="assets/user-data.xml" id="userData" result="contentHandler(event)" resultFormat="e4x"/>
	

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.

		<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" creationComplete="init()">
	

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:

	<mx:Script>
		<![CDATA[
			//actionscript goes here.
		]]>
	</mx:Script>
	

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)

import mx.rpc.events.ResultEvent;

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).

	//Holds complete XML raw file content
	[Bindable] private var userList:XMLList;

	//Changes to Selected Contact's XML Data
	[Bindable] private var selectedData:XML;
	

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.

	//Creation Complete Events
	private function init():void{
		userData.send();
		profileName.text = "No Contact Selected";
	}
	

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.

	private function contentHandler(evt:ResultEvent):void{
		userList = evt.result.user;
	}
	

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.

	private function showProfile(evt:Event):void{
		//Assign data to currently selected item
		selectedData = contactList.selectedItem as XML;
	}
	

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 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.

	<mx:HBox>

		<mx:VBox height="490">
			<mx:DataGrid id="contactList" width="400">
				<mx:columns>
					<mx:DataGridColumn headerText="Contact Name"/>
				</mx:columns>
			</mx:DataGrid>

			<mx:Label fontSize="24" id="profileName"/>
			<mx:Label id="profileJob"/>
			<mx:Label id="profileEmail"/>
		</mx:VBox>	

		<mx:VBox width="360">
			<mx:Image id="profilepic"/>
		</mx:VBox>					

	</mx:HBox>
	

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.

	<mx:HBox>
		<mx:VBox height="490">
			<mx:DataGrid id="contactList" width="400" change="showProfile(event)" dataProvider="{userList}">
				<mx:columns>
					<mx:DataGridColumn dataField="name" headerText="Contact Name"/>
				</mx:columns>
			</mx:DataGrid>

			<mx:Label fontSize="24" id="profileName" text="{selectedData.name}"/>
			<mx:Label id="profileJob" text="Position: {selectedData.position}"/>
			<mx:Label id="profileEmail" text="Email: {selectedData.email}"/>
		</mx:VBox>	

		<mx:VBox width="360">
			<mx:Image id="profilepic" source="{selectedData.image}"/>
		</mx:VBox>					

	</mx:HBox>
	

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:

	<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" creationComplete="init()" backgroundGradientAlphas="[1.0, 1.0]" backgroundGradientColors="[#212121, #010101]">
	

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.

	<mx:Style>
		/*CSS goes here*/
	</mx:Style>
	

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.

	<mx:Style>

			Label{
				color:#FFF;
			}

			HBox{
				backgroundColor:#010101;
				paddingTop:20;
				paddingLeft:20;
				paddingRight:20;
				paddingBottom:20;
			}

	</mx:Style>
	

*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 List

Add Comment

Discussion 34 Comments

  1. Bav says:

    Very interesting. Thanks

  2. Marvin says:

    yeah very nice. could not only used as contact list. very cool. thanks for this!

  3. Gaurav says:

    Nice Tutorials for beginners !!

  4. Sven Peeters says:

    Nice tutorial! For those who are interested in free flex, air and actionscript posters: http://svenpeeters.be/2009/02/gratis-as3-air-en-flex-posters/ (dutch)

  5. mamjed says:

    it would be nice if we could learn how to make AIR apps with flex and flash.

  6. Manish says:

    Very Cool.. We can use this many way..

    Thanks lot…

  7. alvin c. says:

    Nice to see some flex tutorials on the site! Very exciting, also very good tutorial.

  8. Jay says:

    Nice beginner stuff. Im currently working on the advanced version of this with and AdvancedDataGrid for contacts with a quicksearch input and row item editing. Still, this is exactly how its done.

  9. Franky says:

    Nice, we need some more flex action in our lives.

  10. Tassia Pellegrini says:

    Thnaks for this! Very useful!!! Great tuto site like always.

  11. Daniel Toma says:

    Your examples are very instructive and straightforward, in contrast with many other sites out there. It helped me create an application in which I am populating a 6-column datagrid from an external xml file. I ran into a fascinating predicament along the way. The first column in my datagrid was being populated from the contents of my field in the xml file. Of the thousand records in my source file, there was a handful of records in which was empty. It took me a while to realize this, but my application was crashing until I removed them from the source file. Meanwhile, there were other records with empty tags, but none of them were for the FIRST column in the datagrid. Does it seem reasonable to you that the app would go a little nuts when the source data is missing the contents of the field feeding the first column in the datagrid?

    Regards,
    Daniel Toma

  12. Marc says:

    Yay, Flex Stuff, thanks, more like this please.

  13. I think this should of been more of a nettuts tutorial not flashtut’s. The flash tut’s obviously it integrates well with flex. Should of just done the tutorial with flash as / xml.

    We waited so long for a flash tutorial site now not enough being put on it =(.

    Great tutorial though.

    • Zach Dunn says:
      Author

      You know, funny you should mention that. Rest assured Vincent, I tried my hardest to submit Flex tutorials to Nettuts+ before this site launched. They were all turned down because it didn’t fit with the primary audience, which was understandable.

      Flex and Flash belong together, so I’m happy to have a home for these kinds of tutorials.

  14. cyberstar says:

    Yeah, very useful tutorial, more like this , please. But I am not complaining, I wished there is some kind of Flex for beginners for those who are new to FLEX

  15. Design Jar says:

    Not tested Flex before so it looks like this would be a good starting point for someone like myself.

    Cheers

  16. navi says:

    i tried this tutorial, and i am facing a very strange problem… when flex is running the xml is loaded without a problem, but as soon as flex is unloaded from the memory, xml data is no longer loaded into the fields. apparently, it also displays a message that states that the xml file can only be accessed by a swf with previleges, even when my security is very low… please advise.

    • Zach Dunn says:
      Author

      Flex has some security issues when it comes to this. To put it simply you will not be able to load any external files on your local machine without Flex running. Keep in mind that this will not affect the application’s ability to run on a web server.

  17. Imran says:

    Please upload flex stuff as much as you can.. this is wonderful tut..

  18. Misha says:

    just kindergarten…..

  19. Marko says:

    Very nice tutorial and site!! You’re great!!!

  20. Chiz says:

    What about writing to XML? ;-)

  21. Nadun says:

    Can we insert a search function for this? If we’ve tons of contacts, It’ll be easy.. You know what I mean?

  22. bigDeez says:

    How would you go about showing a video instead of a picture?

  23. Matt W says:

    You can not imagine how long I have been looking for a tutorial like this…..I have searched everywhere (or maybe I’m just bad at searching :P)

    Thank you sooo much!

    Great tutorial!

  24. Shoki says:

    Thanks for the Tutorial.

    How do I include this to an existent Catalyst file in Builder?

    I would be very grateful for any ideas!!!

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.