Adobe Flex Flash developer blog

Adventures of a Flex developer

Simple Android Air Highscore (database) example

Wednesday 11 May 2011 by jonnysparkplugs

Flex builder 4.5 makes it pretty simple to persist data within an app.

Air provides the ability to create a SQL lite database, which could be useful for various uses in an application.

In the following example we use the db to score a number and date time stamp.  Bit like a high score table.

The example is pretty simple and all the important logic is handled with in a few functions. The init function is called on load, which then calls two more functions. createdb and updatelistresult. The Create db function checks if the database exists. If not it simply creates a new database.

The update list result function runs a simple command and uses the result as the data provider for the list.


You can download the apk here and the source here

                protected function init(event:FlexEvent):void {  
                     createDb();  
                     updateListResults();  
                }  
                private function createDb():void {  
                     sqlConnection = new SQLConnection();  
                     sqlConnection.open(File.applicationStorageDirectory.resolvePath("hs.db"));  
                     var stmt:SQLStatement = new SQLStatement();  
                     stmt.sqlConnection = sqlConnection;  
                     stmt.text = "CREATE TABLE IF NOT EXISTS highscore (highscoreid INTEGER PRIMARY KEY AUTOINCREMENT, score INTEGER, date DATE)";                      
                     stmt.execute();  
                }                 
                private function updateListResults():void {  
                     var sqlStatement:SQLStatement = new SQLStatement();  
                     sqlStatement.sqlConnection = sqlConnection;  
                     sqlStatement.text = "SELECT * FROM highscore ORDER BY score DESC";  
                     sqlStatement.execute();  
                     var result:SQLResult = sqlStatement.getResult();  
                     listData.source = result.data;  
                }  
                private function addRecord():void {  
                     if(Number(num.text) is Number) {  
                          var sqlStatement:SQLStatement = new SQLStatement();  
                          sqlStatement.sqlConnection = sqlConnection;  
                          sqlStatement.text =  
                               "INSERT INTO highscore (score, date) " +  
                               "VALUES (:score, :date)";  
                          sqlStatement.parameters[":score"] = num.text;  
                          sqlStatement.parameters[":date"] = new Date();  
                          sqlStatement.execute();  
                          updateListResults();  
                     }  
                }  


Filed under having  

0 comments:

Post a Comment