09 - Phonegap Data Storage - Local Storage

Introduction

When you start building real apps, you will of course have to deal with data storage. In a mobile environment, you can store the data either locally on your device or on a different server mainly based on the type of data, volume of data and your data requirements. For example, if you want to store small amount of data that is required frequently, then storing it on your mobile device would be the best option. On the other hand, if you have large volume of data to store, retrieve and update, then it might be better to store on a server.

If you are already familiar with HTML5, you might have used localStorage and sessionStorage objects. As PhoneGap uses HTML5, you can use these same objects for your data storage purposes. You can store data permanently on your mobile device with localStorage. You can store data for a particular session on your mobile device with sessionStorage. If both the above methods are not suitable for your data needs, you can store data on a server.

In this tutorial, we will see how to store data using localStorage.

localStorage Object

If you want to store data permanently on your device without an expiry, then localStorage is the object you need to use. The data stored will be available even if you close your application and try to get it even a year after. We store data as key/value pairs in localStorage. When you store data using localStorage, user experience gets improved considerably because the required data can be fetched so fast without waiting for network connectivity or any other related issues.

The localStorage object offers three methods mainly to deal with data. You can use the setItem method to store the data and you need to pass two parameters to this method, the first parameter being the name of the key and second parameter being the value to be stored. The getItem method is used to get the data stored and you only need to pass the name of the key to fetch its corresponding value. You also have removeItem method if you want to delete a particular data where you need to pass the name of the key to remove it. The data stored in localStorage will be available only to the particular application that creates it. So, there is no need to worry regarding the privacy of the stored data.

Create an App

Let’s create a mobile app for iOS platform this time. Create a project named iOSLocalStorage on the desktop (I am not repeating the steps to create the project as you might already be comfortable with the process.)

Once the project is created on the desktop, open the folder and double click the iOSLocalStorage.xcodeproj icon to launch the project. Now the project is opened in the XCode environment. Again go back to the project folder on the desktop, open the index.html file inside the www folder using your favourite text editor and clean it up. You can also change the title to “Local Data Storage” to make it more relevant.

Suppose the user wants to store his internet banking username and password locally on his machine. Let’s add two textboxes for the user to enter username and password. We will also add two buttons, Save Data and Get Data. On the click of Save Data, we will save the data on the device and on the click of Get Data, we will retrieve the data. We will also add a <div> to display the fetched data.

Add the following lines of code inside the <body> tag.

User Name:<input type="text" id="username" /><br />
Password: <input type="text" id="password" /><br />
<button id="btnSave">Save Data</button><br />
<button id="btnGet">Get Data</button><br />
<div id="result"></div>

Add the following lines of code inside the <head> section to check whether the device is ready. Once the device is ready, we will add the event listeners for the two buttons for their click events.

<script>
            window.onload = function()
            {
                document.addEventListener("deviceready", init, false);
            }
            function init()
            {
                document.getElementById("btnSave").addEventListener("click",saveData, false);
                document.getElementById("btnGet").addEventListener("click", getData, false);
            }
  </script>

Next, we need to write the saveData and getData functions. Inside the saveData function, we will write the code to store the data using setItem method. Inside the getData function, we will get the data using getItem method and then display it on the div named result. Add the following lines of code after the init function.

function saveData()
 {
                var username = document.getElementById("username").value;
                var password = document.getElementById("password").value;
                window.localStorage.setItem("uname", username);
                window.localStorage.setItem("pass", password);
                alert("Your data is stored successfuly");
  }
  function getData()
  {
                var output = "Your user name is " +
                              window.localStorage.getItem("uname") +
                              " and your password is " +
                              window.localStorage.getItem("pass");
                document.getElementById("result").innerHTML = output;
  }

I have first collected the values entered by the user into two variables username and password. Then, I passed those values as the second parameter of the setItem method. Here, I have named the keys as uname and pass. You can name them the way you want. Only thing is that you need to pass the same name as the argument to the setItem method inside the getData function. Now your index.html file will look like this:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta name="format-detection" content="telephone=no" />
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
        <title>Local Data Storage</title>
        <script type="text/javascript" src="cordova.js"></script>
        <script>
            window.onload = function()
            {
                document.addEventListener("deviceready", init, false);
            }
            function init()
            {
                document.getElementById("btnSave").addEventListener("click",saveData, false);
                document.getElementById("btnGet").addEventListener("click", getData, false);
            }
            function saveData()
            {
                var username = document.getElementById("username").value;
                var password = document.getElementById("password").value;
                window.localStorage.setItem("uname", username);
                window.localStorage.setItem("pass", password);
                alert("Your data is stored successfuly");
            }
            function getData()
            {
                var output = "Your user name is " +
                              window.localStorage.getItem("uname") +
                              " and your password is " +
                              window.localStorage.getItem("pass");
                document.getElementById("result").innerHTML = output;
            }
        </script>
    </head>
    <body>
        User Name:<input type="text" id="username" /><br />
        Password: <input type="text" id="password" /><br />
        <button id="btnSave">Save Data</button><br />
        <button id="btnGet">Get Data</button><br />
        <div id="result"></div>
    </body>
</html>

Save the index.html file and run the project from the XCode environment. You can select any simulator you want. You might get a screen like this:

first.png

Enter values in the textboxes like this:

second.png

Now click the Save Data button and you will get a screen like this:

third.png

Now let’s check whether the data is available even after we exit the application or close the simulator. Click the Stop button in the XCode environment. Now your app is closed for the time being. Again click the Run button and then click the Get Data button without entering anything in the textboxes and without clicking the Save Data button. Surprisingly, you could see the user name and password as in the following screen.

fourth.png

It means that your data is stored permanently on the device. Now even if you check this after a week or even a year, you will be able to see these details.

Summary

In this tutorial, we have created an app to store some data permanently. Though we have stored single values, a user name and password in this project, you can use this same technique to store even arrays. In short, you can store localStorage object to store data permanently on the device and to improve the user experience.

Like us on Facebook