Search Flex Components Free

Custom Search

July 6, 2009

Using a Web Service to populate a DataGrid with XML data

In this example I will be using XML data that is returned from a remote site. This example retrieves data about web sites (Name and URL). The XML data will be consumed and displayed in a FlexDataGrid control. Make sure you see the next blog about customizing a DataGrid. Here is a sample of the data returned by the program:



Google
http://google.com


Yahoo
http://yahoo.com



In this example, the data returned will be parsed and stored in an ArrayCollection object. Using an ArrayCollection is a good idea because it used in a lot of Flex tags as a data provider. It also include many methods that will allow you to manipulate the data. The following are the steps taken in Flex to retrieve the data and populate the DataGrid.
  1. Create the HttpService tag in Flex and link it to the XML source:
  2. url="http://some.examplewebsite.com/getSitesInXML.php"
    result="handleSiteData(event)" />

    id -- The name assigned to the service
    url -- is the source of the XML
    result -- Specify the name of the function that will handle the results. This function is called automatically. Incidentally, you can also add a method that will be invoked on errors (fault="someMethod()").
    resultFormat -- self explanatory.
  3. Send service request
  4. getSitesService.send();
    This is usually done upon application loading. For example, in the application tag you can add the code:
    applicationComplete="getSitesService.send();"
    Remember the method "handleSiteData()" will be called automatically upon successful return of the web service. Now, let's look at the method that will handle the returned result.

  5. Handle Site Data (Parse XML data)
    
    
    [Bindable]
    private var siteList:ArrayCollection;
    public function handleSiteData(event:ResultEvent):void {
    xmlData = XMLList(event.result);
    var siteArray:Array = new Array();
    for (var i:int = 0; i < xmlData.site.length(); i++) {
    //Create an object of type Site.
    //Site is a simple ActionScript class
    //that incldes a URL and a Name
    var s:Site = new Site(xmlData.site[i].URL,
    xmlData.site[i].Name);
    //Add the object to the array
    siteArray.push(s);
    }
    //Convert the array to an ArrayCollection
    siteList = new ArrayCollection(siteArray);
    }

    Now we have an 
    ArrayCollection of sites. This collection will be used as the "dataProvider" for the DataGrid control.

  6. Define the DataGrid Control to use the ArrayCollection "siteList" defined above.

Related Flex Tutorials