Create offline Web applications on mobile devices with HTML5 Dietmar Krueger ([email protected]) IT Architect IBM 18 May 2010 Writing applications for multiple operating systems and a wide range of mobile devices can be challenging. The high demand for sophisticated mobile applications requires significant hardware. One solution is to provide Web applications, because they can run cross-platform on mobile devices. You don't need to use proprietary technology (such as Objective-C with Cocoa on the iPhone); you can use common Web technology. In essence, just one version of the application is needed. The main hardware power is provided by servers. In this article, explore the use of Web development in the mobile application space with a simple example that taps into the HTML5 standard. Introduction The use of Web development in mobile applications is an increasing trend. However, intermittent network availability is a big obstacle to using Web technology as part of a cloud infrastructure. A traditional Web application simply doesn't work without a network. One solution to this problem is to use two features of the HTML5 Standard (see Resources): • Offline Web applications • Client-side database storage The user can use cloud functions on a mobile device, work offline with a locally deployed application on a local database, and share data with the rest of the cloud when going online again. In this article, learn the technical details for a typical usage scenario. A prototype of a simple inventory management application demonstrates the HTML5 technology. Download the source code for the example application in this article from the Download table below. Overview Figure 1 shows an overview of the major components of the sample application architecture. © Copyright IBM Corporation 2010 Create offline Web applications on mobile devices with HTML5 Trademarks Page 1 of 12 developerWorks® ibm.com/developerWorks/ Figure 1. Core elements of an offline Web application HTML page The HTML page, the core of the application, has the model role. It contains the displayed data and the (default) render information. The HTML elements of the page are organized in a hierarchy of the HTML Document Object Model (DOM) tree. User-initiated events cause a conventional request-response cycle with a page load and the execution of associated JavaScript functions. Remarkably, this application consists of a single HTML page without the need for loading of further HTML pages through the request-response cycles. The whole action is on one page. JavaScript The JavaScript element contains the controller functions of the application. HTML elements are bound via event handlers to JavaScript functions. JavaScript can access the HTML DOM tree of the application with all user interface (UI) elements and use it as data input for computation. The results of the processing can be presented to the user by modifying the HTML page. Cascading Style Sheet The Cascading Style Sheet (CSS) describes how the HTML page is rendered. The view task is omitted here to simplify the solution. In this stage of expansion, only the default rendering behavior of the HTML elements are used. For mobile devices, there are various JavaScript/CSS libraries and frameworks to deliver a near native user experience with Web applications (for example, iUi for the iPhone). See Resources for more information. Though necessary to increase the user acceptance, this approach has the disadvantage of platform dependency. Create offline Web applications on mobile devices with HTML5 Page 2 of 12 ibm.com/developerWorks/ developerWorks® Database The HTML5 standard introduced local database storage. It is implemented in current versions of the Apple® Safari browser. The browser provides an embedded database, with SQLite, that can be accessed from the JavaScript by processing SQL queries. The business data of the application model is stored here. Manifest The manifest file is the mandatory deployment descriptor component for an offline Web application. It simply lists all the files that need to be loaded. Sample application This section provides an overview of the sample application, called MyHomeStuff. It is a simple inventory management application that lets you keep track of items you own. Figure 2 shows the application on the iPhone. Figure 2. iPhone view For simplicity, the synchronization of data with the server is omitted. Figure 3 shows the MyHomeStuff inventory management application in the Palm Pre Web browser. Create offline Web applications on mobile devices with HTML5 Page 3 of 12 developerWorks® ibm.com/developerWorks/ Figure 3. Palm Pre view The list in the upper part of the screen gives an overview of all entered items (books, computer, and so on). When a user selects an item in the list, the details (Id, Quantity, Name) of the item are shown in the middle of the form. The details of the selected item can be changed using the Update button. The selected item can also be deleted from the application using the Delete button. New items can be created by entering the item's quantity and name in the form and selecting the Create button. The application Status is displayed in the lower part of the screen. HTML details The HTML page contains declarations, meta tags for a mobile-optimized display, references to external files (manifest, JavaScript, css), and essential HTML elements that form the basic structure of the application. Listing 1 shows the code. Listing 1. HTML code <!DOCTYPE HTML> <html manifest="MyHomeStuff.manifest"> <head> <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"> <title>MyHomeStuff</title> <script type="text/javascript" src="MyHomeStuff.js" ></script> </head> <body onload="onInit()"> Create offline Web applications on mobile devices with HTML5 Page 4 of 12 ibm.com/developerWorks/ developerWorks® <h3>Overview</h3> <ul id="itemData" ></ul> <h3>Details</h3> <form name="itemForm"> <label for="id">Id: </label> <input type="text" name="id" id="id" size=2 disabled="true"/> <label for="amount">Amount: </label> <input type="text" name="amount" id="amount" size = 3/> <label for="name">Name: </label> <input type="text" name="name" id="name" size=16 /> <br> <br> <input type="button" name="create" value="create" onclick="onCreate()" /> <input type="button" name="update" value="update" onclick="onUpdate()" /> <input type="button" name="delete" value="delete" </form> <h4>Status</h4> <div id="status"></div> </body> </html> Event handler attributes of the HTML elements specify which JavaScript functions are executed when the page is initially loaded (onload) and button elements are clicked (onclick). The HTML page of an offline Web application starts with the tag <!DOCTYPE HTML>. The manifest is referenced through the manifest attribute in the tag <html manifest="MyHomeStuff.manifest">. As mentioned, the manifest specifies the required files that need to be loaded into the cache. This application consists of an HTML file and a JavaScript file. The HTML file with the reference to the manifest is automatically included in the application cache. The manifest contains only the following: Listing 2. Manifest file CACHE MANIFEST MyHomeStuff.js JavaScript details The JavaScript code consists of three main blocks: • Initialization functions • db (crud) and view update functions • Some little utility functions The first block contains the event handler to initialize the application (onload) and the initialization of the database, as shown in Listing 3. Listing 3. JavaScript init code function onInit(){ try { if (!window.openDatabase) { updateStatus("Error: DB not supported"); } Create offline Web applications on mobile devices with HTML5 Page 5 of 12 developerWorks® ibm.com/developerWorks/ else { initDB(); createTables(); queryAndUpdateOverview(); } } catch (e) { if (e == 2) { updateStatus("Error: Invalid database version."); } else { updateStatus("Error: Unknown error " + e + "."); } return; } } function initDB(){ var shortName = 'stuffDB'; var version = '1.0'; var displayName = 'MyStuffDB'; var maxSize = 65536; // in bytes localDB = window.openDatabase(shortName, version, displayName, maxSize); } In the code above: • The onInit function first checks the existence of the mandatory openDatabase function, whose absence signals that the browser doesn't support a local database. • The initDB function opens the database of the HTML5 browser. • After successfully opening the database, the SQL DDL to create the database table is executed. Lastly, the functions that query the existing records and populate the HTML page with the data are called. Each function of the second JavaScript block has a part for DB access and presentation logic. This consolidation of logic is characteristic of a Model 1 architecture (see Resources), which is the easiest way to develop simple Web applications. For a real-world scenario, an architecture with a clear separation of the Model View Controller (MVC) parts would be appropriate. To build the example overview list, the queryAndUpdate function is called from the event handler functions. Listing 4 shows the code. Listing 4. JavaScript overview code function queryAndUpdateOverview(){ //remove old table rows var dataRows = document.getElementById("itemData").getElementsByClassName("data"); while (dataRows.length > 0) { row = dataRows[0]; document.getElementById("itemData").removeChild(row); }; //read db data and create new table rows var query = "SELECT * FROM items;"; try { localDB.transaction(function(transaction){ transaction.executeSql(query, [], function(transaction, results){ Create offline Web applications on mobile devices with HTML5 Page 6 of 12 ibm.com/developerWorks/ developerWorks® for (var i = 0; i < results.rows.length; i++) { var row = results.rows.item(i); var li = document.createElement("li"); li.setAttribute("id", row['id']); li.setAttribute("class", "data"); li.setAttribute("onclick", "onSelect(this)"); var liText = document.createTextNode(row['amount'] + " x "+ row['name']); li.appendChild(liText); document.getElementById("itemData").appendChild(li); } }, function(transaction, error){ updateStatus("Error: " + error.code + "<br>Message: " + error.message); }); }); } catch (e) { updateStatus("Error: Unable to select data from the db " + e + "."); } } In the code above: • • • • The old data is removed from the DOM tree. A query to select all data sets is executed. For every data set in the result, an HTML list element is created and appended to the list. An event handler, onSelect, is added to every list element to respond on a click. The functions of this block also contain the event handler for the button bar and the list with onUpdate, onDelete, onCreate, and onSelect. Listing 5 shows the code for onUpdate. (onCreate and onDelete have a similar structure, so aren't shown here; you can download all the source code for the example application from the table below.) Listing 5. JavaScript update code function onUpdate(){ var id = document.itemForm.id.value; var amount = document.itemForm.amount.value; var name = document.itemForm.name.value; if (amount == "" || name == "") { updateStatus("'Amount' and 'Name' are required fields!"); } else { var query = "update items set amount=?, name=? where id=?;"; try { localDB.transaction(function(transaction){ transaction.executeSql(query, [amount, name, id], function(transaction, results){ if (!results.rowsAffected) { updateStatus("Error: No rows affected"); } else { updateForm("", "", ""); updateStatus("Updated rows:" + results.rowsAffected); queryAndUpdateOverview(); } }, errorHandler); Create offline Web applications on mobile devices with HTML5 Page 7 of 12 developerWorks® ibm.com/developerWorks/ }); } catch (e) { updateStatus("Error: Unable to perform an UPDATE " + e + "."); } } } In the above code: • The field values of the form are read and validated. • If the values are valid, the update query will be executed. • The result of the query is shown in the updated HTML page. The onSelect function is executed when the user selects a list element. The details form will be filled with the data of this element using the code in Listing 6. Listing 6. JavaScript select code function onSelect(htmlLIElement){ var id = htmlLIElement.getAttribute("id"); query = "SELECT * FROM items where id=?;"; try { localDB.transaction(function(transaction){ transaction.executeSql(query, [id], function(transaction, results){ var row = results.rows.item(0); updateForm(row['id'], row['amount'], row['name']); }, function(transaction, error){ updateStatus("Error: " + error.code + "<br>Message: " + error.message); }); }); } catch (e) { updateStatus("Error: Unable to select data from the db " + e + "."); } } In the code above: • The ID of the selected element is determined. • A select-query is executed. • A function to update the detail form with the read data set is called. The last JavaScript block with utility functions starts with data handlers, which are needed as parameters for the queries. Listing 7. JavaScript handler code errorHandler = function(transaction, error){ updateStatus("Error: " + error.message); return true; } nullDataHandler = function(transaction, results){ } Create offline Web applications on mobile devices with HTML5 Page 8 of 12 ibm.com/developerWorks/ developerWorks® To avoid redundancy, utility functions fill the fields of the detail form (updateForm) and status message (updateStatus), as shown below. Listing 8. JavaScript util code function updateForm(id, amount, name){ document.itemForm.id.value = id; document.itemForm.amount.value = amount; document.itemForm.name.value = name; } function updateStatus(status){ document.getElementById('status').innerHTML = status; } Deployment An iPhone 3GS and a Palm Pre were used to run the example on a real HTML5 mobile device. A current Safari browser on a computer also works. You can download and deploy the files for the application in an HTTP server from the Download table below. The manifest file must be served by the HTTP server with the text/cache-manifest Mime type. After opening the application on the iPhone, save the Bookmark and go in the offline airplane mode. The application will then be opened when the bookmark is selected, and it works without a network. Summary The focus of this article was the technical angle for offline Web applications. A prototype of a simple inventory management application demonstrated the HTML5 technology with a locally deployed application and a local database. Create offline Web applications on mobile devices with HTML5 Page 9 of 12 developerWorks® ibm.com/developerWorks/ Downloads Description Name Size Source code for this article OfflineWebAppSrc.zip 3KB Create offline Web applications on mobile devices with HTML5 Page 10 of 12 ibm.com/developerWorks/ developerWorks® Resources Learn • "Safari Client-Side Storage and Offline Applications Programming Guide" (Apple Inc., 20 Jan 2010) provides details on the JavaScript database support of HTML5. • "ABI Research: Cloud computing will transform mobile apps" (Dusan Belic, 2009) explores Web-based technologies as the prevailing model for mobile applications, where only one version of the application would be needed. • "HTML 5 - A vocabulary and associated APIs for HTML and XHTML" (W3C Working Draft, 4 Mar 2010) is the definitive source on HTML5. • Read iUi: iPhone User Interface Framework to learn more about WebApp development on iPhone-class devices. iUi is a framework consisting of a JavaScript library, CSS, and images for developing advanced mobile WebApps for iPhone and comparable/compatible devices. • "Mobile app dev trends: Making life easier for developers" (John K. Waters, Jul 2009) discusses the trend toward Web development in the mobile space. • Learn more about the Model 1 design model for Java Web applications. With Model 1, a request is made to a JSP or servlet, and then that JSP or servlet handles all responsibilities for the request, including processing the request, validating data, handling the business logic, and generating a response. • The developerWorks Web development zone specializes in articles covering various Webbased solutions. • IBM technical events and webcasts: Stay current with developerWorks' technical events and webcasts. • developerWorks on-demand demos: Watch demos ranging from product installation and setup for beginners, to advanced functionality for experienced developers. Get products and technologies • Evaluate IBM products in the way that suits you best: Download a product trial, try a product online, use a product in a cloud environment, or spend a few hours in the SOA Sandbox learning how to implement Service Oriented Architecture efficiently. Discuss • My developerWorks: Connect with other developerWorks users while exploring the developer-driven blogs, forums, groups, and wikis. Create offline Web applications on mobile devices with HTML5 Page 11 of 12 developerWorks® ibm.com/developerWorks/ About the author Dietmar Krueger Dietmar Krueger works for Application Innovation Services, a Service Line of IBM Global Business Services. He has developed object-oriented software for 17 years. Dietmar has a passion for agile software development, lightweight architectures, and dynamically-typed programming languages. © Copyright IBM Corporation 2010 (www.ibm.com/legal/copytrade.shtml) Trademarks (www.ibm.com/developerworks/ibm/trademarks/) Create offline Web applications on mobile devices with HTML5 Page 12 of 12