Cordova Storage - Cordova

What is Cordova Storage?

We can use storage API available for storing data on the client apps. This will help usage of the app when user is offline and it can also improve performance. Since this is tutorial for beginners we will show you how to use local storage. In one of our later tutorials we will show you other plugins that can be used.

Step 1 - Adding Buttons

We will create four buttons in index.html file. The buttons will be located inside div class = "app" element.


Cordova - Storage

Step 2 - Adding Event Listeners

Cordova security policy doesn't allow inline events so we will add event listeners inside index.js files. We will also assign window.localStorage to a localStorage variable that we will use later.

Step 3 - Creating Functions

Now we need to create functions that will be called when the buttons are tapped. First function is used for adding data to local storage.

The next one will log data we added to console.

If we tap SET LOCAL STORAGE button, we will set three items to local storage. If we tap SHOW LOCAL STORAGE afterwards, the console will log items that we want.

Cordova - Storage

Now let's create function that will delete the project from the local storage.

If we click SHOW LOCAL STORAGE button after we deleted the project, the output will show null value for the project field.

Cordova - Storage

We can also get the local storage elements by using key() method which will take the index as an argument and return the element with corresponding index value.

Now when we tap the GET BY KEY button we will get the following output.

Cordova - Storage

NOTE

When we use key() method the console will log job instead of the name even though we passed argument 0 to retrieve first object. This is because local storage is storing data in alphabetical order.

The following table shows all local storage methods available.

SN

Methods & Details

1

setItem(key, value)

Used for setting the item to local storage

2

getItem(key)

Used for getting the item from local storage.

3

removeItem(key)

Used for removing the item from local storage.

4

key(index)

Used for getting the item by using theindexof the item in local storage. Items are sorted alphabetically

5

length()

Used for retreiving the number of items that exists in local storage.

6

clear()

Used for removing all the key/value pairs from local storage.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Cordova Topics