Flex PieChart with XML input

May 12, 2010

I have been working hard to compile statistics on my photo blog. Currently I have most visited photos and photos by camera. I wanted to create a dynamic chart and luckily, Flex 3 has a charting component that was easy to use. There were a lot of tutorials out there on Flex Charts (mostly bar charts) and a lot of tutorials on pulling XML but not one that combined the two.

Demo:

This demo pulls real time data from my photoblog using XML. I could have hard coded in the data but then it wouldn’t be flexible and every time I uploaded a file I would have to update the chart.

ALTERNATE CONTENT

Code:

<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" backgroundColor="white" creationComplete="siteData.send()" height="600" width="540">

<mx:HTTPService url="http://jessclark.com/photo/stats/flex/cameras.xml.php" id="siteData" resultFormat="e4x" result="serv_result(event)"/>

<mx:Script>

<![CDATA[

import mx.rpc.events.ResultEvent;

[Bindable] private var fullXML:XMLList;

public function serv_result(evt:ResultEvent):void {

fullXML = evt.result.page;

}

]]>

</mx:Script>

<mx:PieChart id="pieChart" selectionMode="single" dataProvider="{fullXML}" showDataTips="true" height="242" width="530" x="10" y="0">

<mx:series>

<mx:PieSeries id="pieSeries" field="data" nameField="camera"></mx:PieSeries>

</mx:series>

</mx:PieChart>

<mx:Legend dataProvider="{pieChart}" x="10" width="520" height="340" y="250" color="#000" direction="horizontal"/>

</mx:Application>

Explanation:

Line 3 is an HTTPService that goes out and grabs the XML file and names it “siteData”.

<mx:HTTPService url="http://jessclark.com/photo/stats/flex/cameras.xml.php" id="siteData" resultFormat="e4x" result="serv_result(event)"/>

Above that, on line 2, creationComplete says that once the application has loaded run the HTTPService.

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" backgroundColor="white" creationComplete="siteData.send()" height="600" width="540">

In the ActionScript (lines 6-11), this takes that results from the HTTPService and captures it in the variable fullXML.

import mx.rpc.events.ResultEvent;

[Bindable] private var fullXML:XMLList;

public function serv_result(evt:ResultEvent):void {

fullXML = evt.result.page;

}

Then we have our PieChart, with a dataProvider of “fullXML” and in the PieSeries the field is called “data” which corresponds to the xml file (same with nameField).

<mx:PieChart id="pieChart" selectionMode="single" dataProvider="{fullXML}" showDataTips="true" height="242" width="530" x="10" y="0">

...

<mx:PieSeries id="pieSeries" field="data" nameField="camera"></mx:PieSeries>

The Legend uses “pieChart” as its dataProvider.

<mx:Legend dataProvider="{pieChart}" x="10" width="520" height="340" y="250" color="#000" direction="horizontal"/>

Tags: , , , ,

Leave a Reply