28
Jul
07

Loading files using the URLLoader and URLVariables classes

Not sure if this is helpful to anybody, but thought I’d throw it out there. The following basic example loads some random variables from an external text file and displays the events which were dispatched in a DataGrid control, as well as the loaded name/value pairs.

Full code after the jump.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="horizontal" verticalAlign="middle" backgroundColor="white" creationComplete="init()"> 

    <mx:Script>
        <![CDATA[
            import mx.collections.ArrayCollection; 

            [Bindable]
            private var VARIABLES_URL:String = "params.txt"; 

            [Bindable]
            private var arrColl:ArrayCollection; 

            [Bindable]
            private var paramColl:ArrayCollection; 

            private var urlReq:URLRequest;
            private var urlLdr:URLLoader; 

            private function init():void {
                /* Initialize the two ArrayCollections objects with empty arrays. */
                arrColl = new ArrayCollection();
                paramColl = new ArrayCollection(); 

                /* Initialize the URLRequest object with the URL to the file of name/value pairs. */
                urlReq = new URLRequest(VARIABLES_URL); 

                /* Initialize the URLLoader object, assign the various event listeners, and load the specified URLRequest object. */
                urlLdr = new URLLoader();
                urlLdr.addEventListener(Event.COMPLETE, doEvent);
                urlLdr.addEventListener(Event.OPEN, doEvent);
                urlLdr.addEventListener(HTTPStatusEvent.HTTP_STATUS, doEvent);
                urlLdr.addEventListener(IOErrorEvent.IO_ERROR, doEvent);
                urlLdr.addEventListener(ProgressEvent.PROGRESS, doEvent);
                urlLdr.addEventListener(SecurityErrorEvent.SECURITY_ERROR, doEvent);
                urlLdr.load(urlReq);
            } 

            private function doEvent(evt:Event):void {
                arrColl.addItem({type:evt.type, idx:arrColl.length+1, eventString:evt.toString()}); 

                switch (evt.type) {
                    case Event.COMPLETE:
                        /* If the load was successful, create a URLVariables object from the URLLoader.data property and populate the paramColl ArrayCollection object. */
                        var ldr:URLLoader = evt.currentTarget as URLLoader;
                        var vars:URLVariables = new URLVariables(ldr.data);
                        var key:String; 

                        for (key in vars) {
                            paramColl.addItem({key:key, value:vars[key]});
                        } 

                        params.visible = true;
                        break;
                }
            }
        ]]>
    </mx:Script> 

    <mx:VBox>
        <mx:Label text="Events:" />
        <mx:DataGrid id="events" dataProvider="{arrColl}" rowCount="5">
            <mx:columns>
                <mx:DataGridColumn dataField="idx" headerText="#" width="20" />
                <mx:DataGridColumn dataField="type" headerText="Type" showDataTips="true" dataTipField="eventString" />
            </mx:columns>
        </mx:DataGrid>
    </mx:VBox> 

    <mx:VBox>
        <mx:Label text="Parameters:" />
        <mx:DataGrid id="params" dataProvider="{paramColl}" rowCount="5" visible="false">
            <mx:columns>
                <mx:DataGridColumn dataField="key" headerText="Key" />
                <mx:DataGridColumn dataField="value" headerText="Value" />
            </mx:columns>
        </mx:DataGrid>
    </mx:VBox> 

</mx:Application>

8 Responses to “Loading files using the URLLoader and URLVariables classes”


  1. 1 Des Jul 31st, 2007 at 12:02 am

    This was helpful to me. I’m porting a small Java Swing based application to Flex which stored individual user information in .properties files (One for each user.) I’ve been looking for several days for informationhow to load and read text based properties in Flex. Thanks for posting

  2. 2 Harry Dec 2nd, 2008 at 5:54 am

    I’ve been searching for solution on unload the data loaded using URLLoader by clicking a checkbox. Any help will be appreciated. Thanks.

  3. 3 Tom Jan 5th, 2009 at 12:00 pm

    this was helpful to me. I’m new to Flex and reading code that uses the URLLoader helps.

  4. 4 Dharmendra Jan 6th, 2009 at 2:47 am

    HI,
    I tried this code with following content in txt file:-

    age= 28
    name= Dharmendra

    It always reads first key value pair.ie it does not load secont key value pair.
    Do we need any kind of saperator in order to read all key value pair properly.

    Thanks,
    Dharmendra

  5. 5 Krishna Jan 28th, 2009 at 12:27 am

    Hi Dharmendra,
    I have some requirement like you have. Please let me know, if you find any solution.
    Regards,
    Krishna

  6. 6 Mandy Feb 11th, 2009 at 12:53 am

    Can i set this [Bindable]
    private var VARIABLES_URL:String = “params.txt”;
    to a php page?

  7. 7 buzo Apr 8th, 2009 at 11:47 am

    Hi Dharmendra:

    from the Flex docs, it seems that the URLVariables class is meant to be used for passing url parameters when constructing a request going from the client to the server (in here is being used for parsing properties which is slightly different). What I’ve found is that the URLVariables class tokenizes the variables using the & as a delimiter, so:

    var vars:URLVariables = new URLVariables(”a=foo&b=baz&c=bar”);

    will be correctly split as name-value pairs. This is the reason why you only see the first name-value pair from your properties file, as this file uses a new line character as the tokenizer.

    I got the example provided above to work by replacing the code:

    var vars:URLVariables = new URLVariables(ldr.data);
    var key:String;

    for (key in vars) {
    paramColl.addItem({key:key, value:vars[key]});
    }

    with:

    var lines:Array = ( ldr.data as String ).split( “\n” );

    for each ( var line:String in lines ) {
    var pair:Array = line.split( “=” );
    paramColl.addItem( { key:pair[0], value:pair[1] } );
    }

    Thank you very much to Peter for sharing the snippet.

  8. 8 Alice Apr 15th, 2009 at 8:11 am

    I am having problems with this URLLoader. When I run the app, I initialize a URLLoader object to get my XML. The first I get my data it’s find. I go to update the data, the data is sent from Flex to a webservice. The webservice saves the data. Trust. I checked. It did overwrite the file and save properly. Flex received word that the webservice call was successfully, so go to load that same xml file again. It loads, but it loads the previous stuff, not exactly the new file. What am I doing wrong?

Leave a Reply

This blog is terrible at eating HTML tags. If you plan on posting code/XML, please escape your "<" characters as "&lt;" and your ">" characters as "&gt;".




July 2007
M T W T F S S
    Aug »
 1
2345678
9101112131415
16171819202122
23242526272829
3031  

Badge Farm

  • Powered by Redoable 1.2
  • Cornify
  • Feeds burnt by Feedburner
  • Feed