Loading files using the URLLoader and URLVariables classes

by Peter deHaan on July 28, 2007

in ActionScript, URLLoader, URLRequest, URLVariables

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>

{ 9 comments… read them below or add one }

1 Des July 31, 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

Reply

2 Harry December 2, 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.

Reply

3 Tom January 5, 2009 at 12:00 pm

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

Reply

4 Dharmendra January 6, 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

Reply

5 Krishna January 28, 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

Reply

6 Mandy February 11, 2009 at 12:53 am

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

Reply

7 buzo April 8, 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.

Reply

8 Alice April 15, 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?

Reply

9 AlCapone November 19, 2009 at 4:44 am

hey guys,
why dont u just show any simple example about URLLoader instead of this nauseous code?

Reply

Leave a Comment

Sorry, this blog is terrible at eating HTML comments.
If you're pasting any HTML/XML/MXML code, you need to convert your < characters to &lt; and your > characters to &gt; .

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Anti-Spam Protection by WP-SpamFree

Previous post:

Next post: