Storage

The Cordova Storage API provides the ability to access the device storage options based on three popular W3C specifications:

  • Web Storage API Specification, which allows you to access data using simple key/value pairs (which we will demonstrate in our "Storage" demo).
  • Web SQL Database Specification, which offers full-featured database tables, which can be accessed using SQL. Note that this option is only available in Android, iOS, BlackBerry 10, and Tizen and not supported on other platforms.
  • IndexedDB Specification is an API for the client-side storage and high performance. It searches on the stored data using indexes. Note that this option is available in Windows Phone 8 and BlackBerry 10.

Demo

In order to use the Storage API, there is no need for a CLI command to run, as it is built in Cordova. In order to access the Storage demo, you can do it by clicking on the Storage list item. You will be introduced to the Storage page. On the Storage page, the users can enter their names and valid e-mails and then click on the Save button in order to save the information, as shown in the following screenshot:

Demo

Saving user information

You can exit the app and then open the Storage page again; you will find that your saved information is reflected in the Name and Email fields. At any point, you can click on the Reload button in order to reload input fields with your saved data.

The HTML page

The following code snippet shows the "storage" page:

<div data-role="page" id="storage">
    <div data-role="header">
        <h1>Storage</h1>
        <a href="#" data-role="button" data-rel="back" data-icon="back">Back</a>
    </div>
    <div data-role="content">
        <h1>Welcome to the Storage Gallery</h1>
        <p>Persist your information using Cordova Web Storage API.</p>
        <form id="storageForm">
            <div class="ui-field-contain">
                <label for="userName">Name</label>
                <input type="text" id="userName" name="userName"></input>
            </div>
            <div class="ui-field-contain">
                <label for="userEmail">Email</label>
                <input type="text" id="userEmail" name="userEmail"></input>
            </div>

            <div class="center-wrapper">
                <input type="button" id="saveInfo" data-icon="action" value="Save" data-inline="true"/>
                <input type="button" id="reloadInfo" data-icon="refresh" value="Reload" data-inline="true"/>
            </div>
            
            <ul id="storageMessageBox"></ul>
            
            <div id="storageResult">
            </div>
        </form>
    </div>
</div>

The preceding "storage" page contains the following:

  • A page header that includes a back button
  • Page content that includes the "storageForm" form, which includes the following elements:
    • "userName": This is the user's name text field
    • "userEmail": This is the user's email text field
    • "saveInfo": This button is used to persist user information
    • "reloadInfo": This button is used to reload saved user information in the "userName" and "userEmail" fields
    • "messageBox": This is an unordered list that displays form validation errors
    • "storageResult": This is a div that displays the storage operation result

View controller

The following code snippet shows the "storage" page view controller JavaScript object that includes the event handlers of the page (storage.js):

(function() {
    var storageManager = StorageManager.getInstance();
    var INFO_KEY = "cordovaExhibition.userInfo";

    $(document).on("pageinit", "#storage", function(e) {
        e.preventDefault();

       $("#saveInfo").on("tap", function(e) {
            e.preventDefault();          


            if (! $("#storageForm").valid()) {
                return;
            }

            storageManager.set(INFO_KEY, JSON.stringify({
                                             userName: $("#userName").val(), 
                                             userEmail: $("#userEmail").val()
                                         })
            ); 

            $("#storageResult").html("User Information are saved");
        }); 

        $("#reloadInfo").on("tap", function(e) {
            e.preventDefault();

            reloadUserInfo();   

            $("#storageResult").html("Reloading completes");   
        });
    });

    $(document).on("pageshow", "#storage", function(e) {
        e.preventDefault();

        $("#storageForm").validate({
            errorLabelContainer: "#storageMessageBox",
            wrapper: "li", 
            rules: {
                userName: "required",
                userEmail: {
                    required: true,
                    email: true
                }
            },
            messages: {
                userName: "Please specify user name",
                userEmail: {
                    required: "Please specify email",
                    email: "Please enter valid email"
                }
            }
        }); 

        reloadUserInfo();
    });

    function reloadUserInfo() {
        var userInfo = JSON.parse(storageManager.get(INFO_KEY));

        populateFormFields(userInfo);
    }
    function populateFormFields(userInfo) {
        if (userInfo) {
            $("#userName").val(userInfo.userName);
            $("#userEmail").val(userInfo.userEmail);    
        }        
    }
})();

As shown in the preceding highlighted code snippet, the "pageinit" event handler registers the "tap" event handlers on the "saveInfo" and "reloadInfo" buttons.

Tip

In order to validate our "storage" form, we use the jQuery validation plugin, which can be found at http://jqueryvalidation.org. In order to use the plugin, all we need to do is include the jquery.validate.min.js file below the jquery.js file that will be shown in the index.html file in Finalizing the Cordova Exhibition App section. After including the jQuery validation plugin JS file, we can simply use the plugin by defining the validation rules on the form fields using the form's validate() method and then validate the form using the form's valid() method, as shown in the "storage" page view controller code.

In the "tap" event handler of the "saveInfo" button:

  • The "storageForm" is validated using the $("#storageForm").valid() method.
  • If the form is valid, then both the "userName" and "userEmail" valid input text values are set as attributes in a JSON object, which is converted to a string using JSON.stringify(). Finally, the stringified JSON object is persisted in the device storage by calling the storageManager.set(key, value) specifying key to be INFO_KEY and the value to be the stringified JSON object.

In the "tap" event handler of the "reloadInfo" button:

  • The user information is retrieved by calling reloadUserInfo(). The reloadUserInfo() method calls storageManager.get(INFO_KEY) in order to get the stored stringified JSON object and then use JSON.parse() in order to convert the stringified JSON object to a JSON object (userInfo).
  • Using populateFormFields(userInfo), userInfo is populated to both "userName" and "userEmail" input text elements.

In the "pageshow" event of the "storage" page, our "storageForm" form validation is constructed by specifying the options parameter of the form's validate() method as follows:

  • errorLabelContainer: This is set to "storageMessageBox" to display the validation errors
  • wrapper: This is set to "li" to wrap the error messages in list items
  • rules object is set as follows:
    • userName: This is set to required
    • userEmail: This is set to be an e-mail and required
  • messages object specifies userName and userEmail validation error messages

Finally, in the "pageshow" event of the "storage" page, reloadUserInfo() is called to reload the user information in the "userName" and "userEmail" input text elements.

API

The following code snippet shows StorageManager.js that does a simple wrapping for two localStorage methods:

var StorageManager = (function () {     
    var instance;

    function createObject() {
        return {
            set: function (key, value) {
                window.localStorage.setItem(key, value);
            },
            get: function (key) {
                return window.localStorage.getItem(key);
            }
        };
    };

    return {
        getInstance: function () {
            if (!instance) {
                instance = createObject();
            }

            return instance;
        }
    }; 
})();

As you can see in the preceding highlighted code, StorageManager is a singleton object that has the following methods:

  • set(key, value): This persists the key/value pair in the local storage by calling the window.localStorage.setItem(key, value) method
  • get(key): This gets the stored value using the passed key parameter by calling the window.localStorage.getItem(key) method

Tip

The complete W3C Web Storage specification is available at http://www.w3.org/TR/webstorage/, and you can also look at the W3C Web SQL Database specification at http://dev.w3.org/html5/webdatabase/. Finally, you can look at the W3C IndexedDB specification at http://www.w3.org/TR/IndexedDB/.

Now, we are done with the storage functionality in the Cordova Exhibition app.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.184.102