Tuesday, March 22, 2011

Create a log application using XML and AIR: Part 1

Create a log application using XML and AIR: Part 1:

In this tutorial we will learn how to use XML files with AIR and start creating an application that lets the user write and view logs, that are saved in an XML file.

Firstly, create a button called myWriteButton and an input text field called myText on stage. This is where the user will write his log entries to.

Here is how the code is going to work: we load data from an XML file as a string value, then parse it to an XML object and store it in a temporary local XML object. We do the changes we want to the local XML file, then, when we're ready to save, we simply overwrite the existing file with the new one.

Let's get started. Create a new File object with a reference to the XML file:

var myFile:File = File.documentsDirectory.resolvePath('Air Examples/mylog2.xml');

Create the local XML object:

var localXML:XML;

And set the text field to blank:

myText.text = '';

Now we need to update the XML object with the information from the real XML file, call the getXML() method:

getXML();

Now, the method itself. If the file we linked to exists - read from it and set localXML to that data. If it doesn't exist - create new one with starting and ending tags.

function getXML():void
{
if (myFile.exists)
{
var myStream:FileStream = new FileStream();
myStream.open(myFile, FileMode.READ);
localXML = new XML(myStream.readUTFBytes(myStream.bytesAvailable));
myStream.close();
}
else
{
localXML = <mylog></mylog>;
}
}

Add a listener for the button:

myWriteButton.addEventListener(MouseEvent.CLICK, writeEntry);

The function for the button appends a child to the local XML and updates the XML on the hard drive:

function writeEntry(evt:MouseEvent):void
{
localXML.appendChild(<logentry date={new Date()}>{myText.text}</logentry>);
myText.text = "";
saveXML();
}

To save the XML, we use saveXML() method, which overwrites the existing file or creates a new one if there isn't one already:

function saveXML():void
{
var myStream:FileStream = new FileStream();
myStream.open(myFile, FileMode.WRITE);
myStream.writeUTFBytes(localXML.toXMLString());
myStream.close();
}

Here's the full code[...]

No comments:

Post a Comment