Thursday, December 5, 2024

Apache Cordova Persistence Options

Apache Cordova Persistence Options

Depending on your particular role where you work, you might be more inclined to develop you applications using either server-side or client-side coding languages. Even generalists who do both tend to lean more towards one or the other. What ever your preference, there is a mobile development framework for you. In my last article, Create a Vaadin Mobile App Project in Eclipse, I introduced a framework that targets Java developers who don’t want to concern themselves with JavaScript and other client-side web languages. Today’s topic, Apache Cordova, takes an entirely different approach, and relies entirely on web technologies such as HTML, CSS, and JavaScript to achieve the same end. In this article, we’ll learn how Apache Cordova’s use of client-side technologies opens up a wealth of storage possibilities.

More on How Apache Cordova Works

Before we get into the topic at hand, let’s quickly review what Apache Cordova is and how it operates.

Apache Cordova became a top level project within the Apache Software Foundation (ASF) in October of 2012. It’s a free and open source framework licensed under the Apache License, Version 2.0.

There are a few reasons why the makers of Cordova went with client-side technologies. Besides the obvious side-stepping of older server-side languages such as Java and C++, it allows the framework to be combined with other client-side libraries, including jQuery Mobile, Dojo Mobile, or Sencha Touch. Another notable benefit is that, by employing code that is built on existing web standards, smartphone apps should be portable to other device platforms with minimal or even no changes. Finally, client-side technologies may be developed without the need of any special IDEs – or Integrated Development Environments; all that’s required is a code editor, a modern browser, and a connection to the Internet. Having said that, if you do typically develop using a specialized tool, there is no reason that you can’t continue to use it.

Storage Options at a Glance

Being a client-side framework, Cordova has access to the exact same storage options as any HTML application, based on the browser and device that your app is being run on. Keeping in mind that not every version of every mobile browser supports every storage option, here are your choices:

  • Local Storage – Stores private primitive data in key-value pairs and is generally best for simple data.
  • WebSQL – This API is available in the underlying WebView. The Web SQL Database Specification offers database tables accessed via SQL queries. The following platforms support WebSQL:
    • Android
    • BlackBerry 10
    • iOS
    • Tizen
  • IndexedDB – Also available in the underlying WebView, IndexedDB offers more features than Local Storage but fewer than WebSQL. IndexedDB is supported by the following platforms:
    • BlackBerry 10
    • Windows Phone 8
    • Windows 8
  • Plugin-Based Options – In addition to the storage APIs listed above, the File API allows you to cache data on the local file system. Other Cordova plugins provide similar storage options.
  • SQLite Databases – Stores structured data in a private database.
  • Network Connection – Store data on the web with your own network server.

Deciding Which Type of Storage to Use

The decision about which of storage options you choose often generally on the following factors:

  1. Application Properties – You can use Local Storage here.
  2. Database – You should use SQLite if you need to store structured data.
  3. Filesystem – You can use the Internal/External storage options.

Some Practical Examples

For the remainder of the article, we’ll take a look at how to use some of the above storage mechanisms.

Local Storage

Here’s something that is available to most modern browsers. Local Storage was an attempt by vendors to eventually do away with cookies. Compared to those, Local Storage is much simpler to use. All of the data is stored in the global localStorage attribute. It’s an associative array so each item is referenced using a key.

Data may be stored via the setItem() method, which accepts a key and value, or directly using square bracket notation:

window.localStorage.setItem('user_id', 'CVB765');
window.localStorage['user_email'] = 'bobm@acme.com';

Ditto for retrieving stored values, except that the retrieval method is getItem() rather than setItem():

var userID = window.localStorage.getItem('user_id');
var userEmail = window.localStorage['user_email'];

Web SQL Database

Web SQL Database will work in latest version of Safari, Chrome and Opera. If you are well versed in SQL and working with databases through programming code, you will find this implementation quite familiar. This code snippet first creates a log table, inserts a few rows into it. The second transaction function fetches the contents of the log table and displays them in the web page.

var db     = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024),
    msg    = '',
    status = document.getElementById('status');
db.transaction(function (tx) {
  tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
  tx.executeSql('INSERT INTO LOGS (id, log) VALUES (1, "Log entry 1")');
  tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, "Log entry 2")');
  msg = '<p>Log message created and row inserted.</p>';
  status.innerHTML =  msg;
});

db.transaction(function (tx) {
  tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) {
   var len = results.rows.length, i;
   msg = "<p>Found rows: " + len + "</p>";
   status.innerHTML +=  msg;
   for (i = 0; i < len; i++){
     msg = "<p><b>" + results.rows.item(i).log + "</b></p>";
     status.innerHTML +=  msg;
   }
 }, null);
});

Conclusion

There are no shortage of storage options available to you when developing with the Apache Cordova Framework. It’s reliance on HTML5-compliant front-end code all but guarantees that the same storage types available to the majority of A class browsers will also be accessible to your mobile apps. In part 2 of this theme, we will examine the remaining storage options in more detail.

Rob Gravelle
Rob Gravelle
Rob Gravelle resides in Ottawa, Canada, and has been an IT guru for over 20 years. In that time, Rob has built systems for intelligence-related organizations such as Canada Border Services and various commercial businesses. In his spare time, Rob has become an accomplished music artist with several CDs and digital releases to his credit.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured