Adobe Flex 3 Help

Creating a shared object

To create a SharedObject object, use the SharedObject.getLocal() method, which has the following syntax:

SharedObject.getLocal("objectName" [, pathname]): SharedObject

The following example creates a shared object called mySO:

public var mySO:SharedObject;
mySO = SharedObject.getLocal("preferences");

This creates a file on the client's machine called preferences.sol.

The term local refers to the location of the shared object. In this case, Adobe® Flash® Player stores the SharedObject file locally in the client's home directory.

When you create a shared object, Flash Player creates a new directory for the application and domain. It also creates an empty *.sol file that stores the SharedObject data. The default location of this file is a subdirectory of the user's home directory. The following table shows the default locations of this directory:

Operating System

Location

Windows 95/98/ME/2000/XP

c:/Documents and Settings/username/user_domain/Application Data/Macromedia/Flash Player/#SharedObjects/web_domain/path_to_application/application_name/object_n ame.sol

Windows Vista

c:/Users/username/user_domain/AppData/Roaming/Macromedia/Flash Player/#SharedObjects/web_domain/path_to_application/application_name/object_n ame.sol

Macintosh OS X

/Users/username/Library/Preferences/Macromedia/Flash Player/#SharedObjects/web_domain/path_to_application/application_name/object_n ame.sol

Linux/Unix

/home/username/.macromedia/Flash_Player/#SharedObjects/web_domain/path_to_appl ication/application_name/object_name.sol

For example, if you request an application named MyApp.mxml on the local host, in the Flex context, and within a subdirectory named /sos, Flash Player stores the *.sol file in the following location on Windows:

c:/Documents and Settings/fred/localhost/Application Data/Macromedia/Flash Player/#localhost/flex/sos/MyApp.mxml.swf/data.sol

Note: If you do not provide a name in the SharedObject.getLocal() method, Flash Player names the file undefined.sol.

Although usually predictable, the location of the SharedObject file can be anywhere that Flash Player has access to within its sandbox and can have any name that Flash Player assigns to it.

By default, Flash can save locally persistent SharedObject objects of up to 100 KB per domain. When the application tries to save data to a shared object that would make it bigger than 100 KB, Flash Player displays the Local Storage dialog box, which lets the user allow or deny local storage for the domain that is requesting access.

Specifying a path

You can use the optional pathname parameter to specify a location for the SharedObject file. This file must be a subdirectory of that domain's SharedObject directory. For example, if you request an application on the localhost and specify the following:

mySO = SharedObject.getLocal("myObjectFile","/");

Flash Player writes the SharedObject file in the /#localhost directory (or /localhost if the application is offline). This is useful if you want more than one application on the client to be able to access the same shared object. In this case, the client could run two Flex applications, both of which specify a path to the shared object that is the root of the domain; the client could then access the same shared object from both applications. To share data between more than application without persistence, you can use the LocalConnection object.

If you specify a directory that does not exist, Flash Player does not create a SharedObject file.

Adding data to a shared object

You add data to a SharedObject's *.sol file using the data property of the SharedObject object. To add new data to the shared object, use the following syntax:

sharedObject_name.data.variable = value;

The following example adds the userName, itemNumbers, and adminPrivileges properties and their values to a SharedObject:

public var currentUserName:String = "Reiner";
public var itemsArray:Array = new Array(101,346,483);
public var currentUserIsAdmin:Boolean = true;
mySO.data.userName = currentUserName;
mySO.data.itemNumbers = itemsArray;
mySO.data.adminPrivileges = currentUserIsAdmin;

After you assign values to the data property, you must instruct Flash Player to write those values to the SharedObject's file. To force Flash Player to write the values to the SharedObject's file, use the SharedObject.flush() method, as follows:

mySO.flush();

If you do not call the SharedObject.flush() method, Flash Player writes the values to the file when the application quits. However, this does not provide the user with an opportunity to increase the available space that Flash Player has to store the data if that data exceeds the default settings. Therefore, it is a good practice to call SharedObject.flush().

Storing objects in shared objects

You can store simple objects such as Arrays or Strings in a SharedObject's data property.

The following example is an ActionScript class that defines methods that control the interaction with the shared object. These methods let the user add and remove objects from the shared object. This class stores an ArrayCollection that contains simple objects.

package {
    import mx.collections.ArrayCollection;
    import flash.net.SharedObject;

    public class LSOHandler {

        private var mySO:SharedObject;
        private var ac:ArrayCollection;
        private var lsoType:String;

        // The parameter is "feeds" or "sites".
        public function LSOHandler(s:String) {
            init(s);
        }

        private function init(s:String):void {
            ac = new ArrayCollection();
            lsoType = s;
            mySO = SharedObject.getLocal(lsoType);
            if (getObjects()) {
                ac = getObjects();
            }
        }

        public function getObjects():ArrayCollection {
            return mySO.data[lsoType];
        }

        public function addObject(o:Object):void {
            ac.addItem(o);
            updateSharedObjects();
        }

        private function updateSharedObjects():void {
            mySO.data[lsoType] = ac;
            mySO.flush();
        }
    }

}

The following Flex application creates an instance of the ActionScript class for each of the types of shared objects it needs. It then calls methods on that class when the user adds or removes blogs or site URLs.

<?xml version="1.0"?>
<!-- lsos/BlogAggregator.mxml -->
<mx:Application 
    xmlns:local="*" 
    xmlns:mx="http://www.adobe.com/2006/mxml" 
    creationComplete="initApp()" 
    backgroundColor="#ffffff"
>
    <mx:Script>
        <![CDATA[
        import mx.collections.ArrayCollection;
        import mx.utils.ObjectUtil;
        import flash.net.SharedObject;

        [Bindable]
        public var welcomeMessage:String;
        
        [Bindable]
        public var localFeeds:ArrayCollection = new ArrayCollection();

        [Bindable]
        public var localSites:ArrayCollection = new ArrayCollection();

        public var lsofeeds:LSOHandler;
        public var lsosites:LSOHandler;

        private function initApp():void {
            lsofeeds = new LSOHandler("feeds");
            lsosites = new LSOHandler("sites");
            
            if (lsofeeds.getObjects()) {
                localFeeds = lsofeeds.getObjects();
            }
            if (lsosites.getObjects()) {
                localSites = lsosites.getObjects();
            }
        }
        
        // Adds a new feed to the feeds DataGrid.
        private function addFeed():void {
            // Construct an object you want to store in the 
            // LSO. This object can contain any number of fields.
            var o:Object = {name:ti1.text, url:ti2.text, date:new Date()};
            lsofeeds.addObject(o);
    
            // Because the DataGrid's dataProvider property is 
            // bound to the ArrayCollection, Flex updates the
            // DataGrid when you call this method. 
            localFeeds = lsofeeds.getObjects();
            
            // Clear the text fields.
            ti1.text = '';        
            ti2.text = '';
        }
        
        // Removes feeds from the feeds DataGrid.
        private function removeFeed():void {
            // Use a method of ArrayCollection to remove a feed.
            // Because the DataGrid's dataProvider property is 
            // bound to the ArrayCollection, Flex updates the
            // DataGrid when you call this method. You do not need
            // to update it manually.
            if (myFeedsGrid.selectedIndex > -1) {
localFeeds.removeItemAt(myFeedsGrid.selectedIndex);
}
} private function addSite():void { var o:Object = {name:ti3.text, date:new Date()}; lsosites.addObject(o); localSites = lsosites.getObjects(); ti3.text = ''; } private function removeSite():void { if (mySitesGrid.selectedIndex > -1) {
localSites.removeItemAt(mySitesGrid.selectedIndex);
}
} ]]> </mx:Script> <mx:Label text="Blog aggregator" fontSize="28"/> <mx:Panel title="Blogs"> <mx:Form id="blogForm"> <mx:HBox> <mx:FormItem label="Name:"> <mx:TextInput id="ti1" width="100"/> </mx:FormItem> <mx:FormItem label="Location:"> <mx:TextInput id="ti2" width="300"/> </mx:FormItem> <mx:Button id="b1" label="Add Feed" click="addFeed()"/> </mx:HBox> <mx:FormItem label="Existing Feeds:"> <mx:DataGrid id="myFeedsGrid" dataProvider="{localFeeds}" width="400" /> </mx:FormItem> <mx:Button id="b2" label="Remove Feed" click="removeFeed()"/> </mx:Form> </mx:Panel> <mx:Panel title="Sites"> <mx:Form id="siteForm"> <mx:HBox> <mx:FormItem label="Site:"> <mx:TextInput id="ti3" width="400"/> </mx:FormItem> <mx:Button id="b3" label="Add Site" click="addSite()"/> </mx:HBox> <mx:FormItem label="Existing Sites:"> <mx:DataGrid id="mySitesGrid" dataProvider="{localSites}" width="400" /> </mx:FormItem> <mx:Button id="b4" label="Remove Site" click="removeSite()"/> </mx:Form> </mx:Panel> </mx:Application>

The executing SWF file for the previous example is shown below:

Storing typed objects in shared objects

You can store typed ActionScript instances in shared objects. You do this by calling the flash.net.registerClassAlias() method to register the class. If you create an instance of your class and store it in the data member of your shared object and later read the object out, you will get a typed instance. By default, the SharedObject objectEncoding property supports AMF3 encoding, and unpacks your stored instance from the SharedObject object; the stored instance retains the same type you specified when you called the registerClassAlias() method.

Creating multiple shared objects

You can create multiple shared objects for the same Flex application. To do this, you assign each of them a different instance name, as the following example shows:

public var mySO:SharedObject = SharedObject.getLocal("preferences");
public var mySO2:SharedObject = SharedObject.getLocal("history");

This creates a preferences.sol file and a history.sol file in the Flex application's local directory.