IT tutorials
 
Mobile
 

Developing BlackBerry Tablet Applications : Working with the File System - SQLite Databases

5/31/2013 7:57:34 PM
- How To Install Windows Server 2012 On VirtualBox
- How To Bypass Torrent Connection Blocking By Your ISP
- How To Install Actual Facebook App On Kindle Fire

Just as within Adobe AIR on the desktop, you can utilize an SQLite database for storing data on a mobile device. The next example will create a database, use a simple form to save data to that database, and retrieve and display the stored data.

Let’s review the following code. At the top, you will see the database file defined as a file called users.db within the userDirectory. Next, the SQLConnection is defined. Finally, several SQLStatements are declared and SQL strings defined, which will be used for working with the database.

Within the applicationComplete event handler, the SQLConnection is initiated, two event listeners are added to listen for SQLEvent.OPEN and SQLErrorEvent.ERROR, and finally, the openAsync method is called and the db file is passed in.

After the database is opened, the openHandler function is called. Within this function, the SQLEvent.OPEN event listener is removed. Next, the createTableStmt is created, configured, and executed. This statement will create a new table called Users if it doesn’t yet exist. If this statement is successful, then the createResult method is called. Within the createResult method, the SQLEvent.RESULT event is removed and the selectUsers method is called.

Within the selectUsers method, the selectStmt is created, configured, and executed. This statement will return all rows within the Users table. This data is then stored within the selectStmt. If this statement is successful, then the selectResult method is called. Within the selectResult method, the data is read from the selectStmt by using the getResults method and is cast to an ArrayCollection and set to the dataProvider of a DataGroup, where it is shown on screen by formatting within an itemRenderer named UserRenderer.

All the processes just described occur as chained events when the application loads up. So if there is any data in the database from previous usage, it will automatically display when the application is loaded. This is shown in Figure 1.

The only remaining functionality is the ability to add a new user. There are two text fields with the IDs of firstName and lastName and a Button that, when clicked, will call the button1_clickHandler function. Within the button1_clickHandler function, the insertStmt is created, configured, and executed. Notice that within the insertStmt configuration, the parameters firstName and lastName that were defined in the insertSQL are set to the text properties of the firstName and lastName TextInput components. If this statement is successful, then the insertResult method is called. Within the insertResult method, the selectUsers method is called, and the DataGroup is updated showing the newly added data. This is shown in Figure 2.

Here is the code for the Main Application:

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
               xmlns:s="library://ns.adobe.com/flex/spark"
               applicationComplete="application1_applicationCompleteHandler(event)">
    <fx:Script>
        <![CDATA[
            import mx.collections.ArrayCollection;
            import mx.events.FlexEvent;

            private var db:File = File. applicationStorageDirectory.
resolvePath("users.db");
            private var conn:SQLConnection;

            private var createTableStmt:SQLStatement;
            private var createTableSQL:String = "CREATE TABLE IF NOT EXISTS User (" +
                                     "userId INTEGER PRIMARY KEY AUTOINCREMENT," +
                                     "firstName TEXT," + "lastName TEXT)";

            private var selectStmt:SQLStatement;
            private var selectSQL:String = "SELECT * FROM User";

            private var insertStmt:SQLStatement;
            private var insertSQL:String = "INSERT INTO User (firstName, lastName)" +
                                           "VALUES (:firstName, :lastName)";

            protected function application1_applicationCompleteHandler
(event:FlexEvent):void
            {
                conn = new SQLConnection();
                conn.addEventListener(SQLEvent.OPEN, openHandler);
                conn.addEventListener(SQLErrorEvent.ERROR, errorHandler);
                conn.openAsync(db);
            }

            private function openHandler(event:SQLEvent):void {
                log.text += "Database opened successfully";
                conn.removeEventListener(SQLEvent.OPEN, openHandler);
                createTableStmt = new SQLStatement();
                createTableStmt.sqlConnection = conn;
                createTableStmt.text = createTableSQL;
                createTableStmt.addEventListener(SQLEvent.RESULT, createResult);
                createTableStmt.addEventListener(SQLErrorEvent.ERROR, errorHandler);
                createTableStmt.execute();
            }

            private function createResult(event:SQLEvent):void {
                log.text += "\nTable created";
                conn.removeEventListener(SQLEvent.RESULT, createResult);
                selectUsers();
            }

            private function errorHandler(event:SQLErrorEvent):void {
                log.text += "\nError message: " +  event.error.message;
                log.text += "\nDetails: " +  event.error.details;
            }

            private function selectUsers():void{
                selectStmt = new SQLStatement();
                selectStmt.sqlConnection = conn;
                selectStmt.text = selectSQL;
                selectStmt.addEventListener(SQLEvent.RESULT, selectResult);
                selectStmt.addEventListener(SQLErrorEvent.ERROR, errorHandler);
                selectStmt.execute();
            }

            private function selectResult(event:SQLEvent):void {
                log.text += "\nSelect completed";
                var result:SQLResult = selectStmt.getResult();
                users.dataProvider = new ArrayCollection(result.data);
            }

            protected function button1_clickHandler(event:MouseEvent):void
            {
                insertStmt = new SQLStatement();
                insertStmt.sqlConnection = conn;
                insertStmt.text = insertSQL;
                insertStmt.parameters[":firstName"] = firstName.text;
                insertStmt.parameters[":lastName"] = lastName.text;
                insertStmt.addEventListener(SQLEvent.RESULT, insertResult);
                insertStmt.addEventListener(SQLErrorEvent.ERROR, errorHandler);
                insertStmt.execute();
            }

            private function insertResult(event:SQLEvent):void {
                log.text += "\nInsert completed";
                selectUsers();
            }

        ]]>
    </fx:Script>
    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
    </fx:Declarations>

    <s:Label text="First name" top="35" left="10"/>
    <s:TextInput id="firstName" left="150" top="10" width="300"/>

    <s:Label text="Last name" top="95" left="10"/>
    <s:TextInput id="lastName" left="150" top="70" width="300"/>

    <s:Button label="Save" click="button1_clickHandler(event)" top="130" left="150"/>

    <s:Scroller height="200" width="100%" left="10" right="10" top="200">
        <s:DataGroup id="users" height="100%" width="95%"
                     itemRenderer="UserRenderer">
            <s:layout>
                <s:VerticalLayout/>
            </s:layout>
        </s:DataGroup>
    </s:Scroller>

    <s:TextArea id="log" width="100%" bottom="0" height="250"/>

</s:Application>

					  

The code for the UserRenderer

<?xml version="1.0" encoding="utf-8"?>
<s:ItemRenderer xmlns:fx="http://ns.adobe.com/mxml/2009"
                    xmlns:s="library://ns.adobe.com/flex/spark">
    <s:Label text="{data.lastName}, {data.firstName}"/>
</s:ItemRenderer>

Figure 1. SQLite sample application


Figure 2. After adding a record

 
Others
 
- Developing BlackBerry Tablet Applications : File System Access (part 3) - File Browse for Multiple Files
- Developing BlackBerry Tablet Applications : File System Access (part 2) - File Browse for Single File
- Developing BlackBerry Tablet Applications : File System Access (part 1)
- iPhone Developer : Assembling Views and Animations - Managing Subviews - Tagging and Retrieving Views
- iPhone Developer : Assembling Views and Animations - Recovering a View Hierarchy Tree, Querying Subviews
- Java ME on Symbian OS : Handling Diversity - Handling Screen and Display Diversity
- Java ME on Symbian OS : Handling Diversity - Handling Diverse Multimedia Formats and Protocols
- Java ME on Symbian OS : Handling Diversity - Supporting Diverse Input Mechanisms
- Windows Phone 7 : Building 2D Games with the XNA Framework - AlienShooter Game Play (part 6) - Updated GameplayScreen Class, Collision Detection and Memory Management
- Windows Phone 7 : Building 2D Games with the XNA Framework - AlienShooter Game Play (part 5) - Missile Class, Game Status Board Class
 
25 Inspiring Game of Thrones Quotes
 
Top 10
 
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 2) - Wireframes,Legends
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 1) - Swimlanes
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Formatting and sizing lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Adding shapes to lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Sizing containers
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 3) - The Other Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 2) - The Data Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 1) - The Format Properties of a Control
- Microsoft Access 2010 : Form Properties and Why Should You Use Them - Working with the Properties Window
- Microsoft Visio 2013 : Using the Organization Chart Wizard with new data
programming4us programming4us
 
Popular tags
 
Video Tutorail Microsoft Access Microsoft Excel Microsoft OneNote Microsoft PowerPoint Microsoft Project Microsoft Visio Microsoft Word Active Directory Biztalk Exchange Server Microsoft LynC Server Microsoft Dynamic Sharepoint Sql Server Windows Server 2008 Windows Server 2012 Windows 7 Windows 8 Adobe Indesign Adobe Flash Professional Dreamweaver Adobe Illustrator Adobe After Effects Adobe Photoshop Adobe Fireworks Adobe Flash Catalyst Corel Painter X CorelDRAW X5 CorelDraw 10 QuarkXPress 8 windows Phone 7 windows Phone 8 BlackBerry Android Ipad Iphone iOS