Saving preferences in Air Applications

Every now and then, while working on a AIR application, i feel the need to save or restore some config info, like the last window position, or the last opened files.

Instead of embedding this login in every app, I thought about a PreferenceManager class that stores and restores values.

How it should behave:

  • It must save data on a file.
  • It must save data on an open and editable format, so if something goes wrong..
  • It should be a static class, so i can access it in every other class of my application, whitout the need to have the reference to the instantiated object.
  • It should be really simple to use. And should not require any setup.


So having stated this, the public interface looks like this:

package
{
    public class Preferences
    {
        public static function set(prefName:String, value:String):void;
        public static function get(prefName:String):String;
    }
}

Preferences will be saved in a file in File.applicationStorageDirectory called preferences.xml, so every Application will have his own preference file.

The usage comes easy, when I want to save a preference, let’s say the last user name entered I’ll

Preferences.set("LastUserEntered", "Carlo");

and next time I open the application, to retrieve the data

var whatWasTheName:String = Preferences.get("LastUserEntered");

This implies two things: when i get a preference that hasn’t been set, the method will return null and I can only save string values.

Sooner or later I’ll talk about reflection and how to serialize any kind of object.

So now go download the Preferences.as class!

Do you want to leave a comment?