Firefox OS Tutorial : Episode 6 : Enabling Storage

Welcome to Episode 6 of the Firefox OS Tutorial. This series will take you through the steps to writing Firefox OS Apps that add the persistence capability to your application. What this means is that you can use a local database of sorts to save your data and the data will be available not just across the application but also across application restarts.

Prerequisites

  • You have setup your machine with the Firefox OS Simulator. If not, you can check out Episode 1, which takes you through the entire setup.
  • You have a basic understanding of writing Firefox OS Apps. If not, I strongly suggest to refer to earlier episodes, especially Episode 2, that covers how to write your first Firefox OS App.

What this Episode covers

  • What is the HTML5 LocalStorage API
  • Sample Firefox OS Application that covers using HTML5 LocalStorage API.

Episode 6 in Action

Let us check out the application in action first. This will help you understand what we shall be achieving by the end of this blog post.

What we shall write is a mobile application that will allow us to save some quick notes. Each note will have a title and some details. These notes will be saved in the Local Storage of the device and then we can view all our notes too.

All right then, the first screen of the mobile app is shown below:

ep6-screen1

When we click on Add a Note button, we get a screen as shown below where we can enter the title and details for the new note. Once we are done, we can save the note by clicking on the Save Note button.

ep6-screen2

If the note is successfully saved, it will display a message as shown below:

ep6-screen3

To view all the notes, you need to click on the View Notes button from the main screen. This will retrieve all the notes from the Local Storage and display them to you in a collapsible list form.

ep6-screen4

You can click on any of the signs and it will expand to show you the note details as shown below:

ep6-screen5

If you wish to delete all the notes, there is also a Clear button. This will delete permanently all the notes from the Local Storage.

Let’s get going with the code. Note that the example screenshots are from the Firefox OS Simulator running locally. So you can use your Firefox OS Simulator to run all the examples.

Download Full Source Code – Episode 6

I suggest that you begin with a full download of the project source code. Since the project depends on libraries like jQuery and jQuery Mobile, it will save you the hassle of downloading the dependent libraries.

Go ahead & download the code from : https://github.com/rominirani/SaveNotes

Extract all the code in some folder. For e.g. on my machine, the code is present in e:\firefox-os-blog\episode6\SaveNotes but it could be any directory of your choice. You should see a folder structure inside of SaveNotes, that looks something like this:

ep6-screen9

HTML5 Storage APIs

The HTML5 Storage API is a JavaScript API that will allow your application to store data and retain that data even across browser restarts. 

As a first step to make web applications work offline, we need a storage API that allows the application to store application specific data and use it as needed. Here are some examples of how you could use storage:

  • Games: You need to store the current moves in an application, so that if the user were to come later later to the application, you can replay back the moves. Save high scores maybe?
  • Business Apps: How about saving information locally. E.g. taking offline orders, writing notes, etc. notes locally and looking them up.

You will easily be able to think of more use cases.

The Storage API also known as the Local Storage API provides a key based storage with a simple API to go along with it. The amount of storage size allocated per domain is anywhere from 5MB-10MB, which should be sufficient for most applications. There is also another API available for storage (IndexedDB), which provides a more sophisticated database like structure a la SQL, but we shall keep the discussion limited now to simple storage support in the form of key-based values.

Few things to do about the Storage API:

  • The Local Storage Object that is provided to you is available under window.localStorage. But for all purposes, you can use as localStorage. All the methods for saving, removing, etc will be invoked in a format that looks like localStorage.<some-method>
  • There are just 6 methods that you need to be familiar with to understand the localStorage API. If you have worked with maps or key-value data structures before in any language, it should be familiar.
  • The methods are:
    • getItem(<key>) : Returns back the value for the key.
    • setItem(<key>,<value>) : Sets a value (Creates or overwrites) for a key.
    • removeItem(<key>) : Deletes the entry for that particular key.
    • clear() : removes all the entries in the Local Storage.
    • length : returns a count of the number of keys in the local storage
    • key(<index>) : returns the value for a key as per the index. The index ranges from 0 to (length-1)

Save Notes Application

OK. Lets get going with understand the code and how the Local Storage API has been used to persist (save) notes in our application.

SaveNotes Application – manifest.webapp

The first thing we should discuss is the manifest file. This should be familiar now and it has the standard attributes like name, version, etc. There is nothing special happening here.

SaveNotes Application – index.html

Next up is the index.html page and it is a simple jQuery Mobile page.

Let us discuss the index.html page in detail now:

  • We have included the script in app.js file. #Line 10
  • There are 3 pages in the mobile application : index (Line # 15), add-notes (Line #27) and view-notes (Line # 40)
  • The #index page has two buttons for Add a Note and View Notes
  • The #add-notes page has a form for entering the title (#noteTile), details (#noteDetails) and a couple of buttons for saving the note (#btnSaveNote) and clearing the fields (#btnClearNotes)
  • The #view-notes page has a button in the header to clear all notes (#clearAllNotesBtn) and it has a div area (#note-list) to display all the current notes, once we get it from the Local Storage.

SaveNotes Application – app.js

Let us discuss the source code in detail now since it contains the HTML5 LocalStorage JavaScript API:

  • Line # 2-5 indicate that when we click on the Add a Note button the index page, it will navigate to the add-notes page. This is jQuery Mobile stuff.
  • Let us first focus on Adding or Saving the note. Line #24 – 32. Here you will notice that we first extract out the value that the user has entered for title and detail. Then on Line #28 , we check if localStorage object is available i.e. support is there. If yes, we simply invoke the localStorage.setItem(<key>,<value>) method. This will save the key-value in the local storage. Note that we are using the title of the note as the key. So if you enter the same title again but with different details, it will overwrite the value because the key is the same. So keep in mind, that setItem method functions as both an Add and an Update. That is all there is to save the item. Note that we have saved a simple string value here, but you could put entire JSON Objects over here (Object, Array) and read back the values.
  • Now let us focus on Line # 6-22.  Line #6 – 8 indicates that when we press the View Notes button on the index page, it will navigate to the view-notes page.
  • We clear the content i.e. any existing items that were present on the page by clearing the html content for #note-list on Line #10
  • Then we iterate through the localStorage keys one by one, retrieve the values and form the jQuery Mobile collapsible div for each note entry. Note that this loop (Line # 12-21 indicate the use of 3 additional methods of the localStorage.
  • We first use the localStorage.length method to get the total number of items that are present.
  • Next we get the key for each item via the localStorage.key(index) method.
  • Finally, we use the localStorage.getItem(<key>) method to retrieve the details for the note.
  • The for each note, we are simply creating a collapsible div for jQuery Mobile UI and appending it to the #note-list element.

Local Installation and Testing

This completes our discussion of writing Firefox OS applications that utilize the HTML5 LocalStorage API. Now comes the part of seeing it actually work. All we need to test out this application is:

  1. You should have installed the Firefox OS Simulator add-on in your Firefox Browser.
  2. A working internet connection from your machine.
  3. You should have downloaded/written the application as described above. We will assume that the index.html and manifest.webapp file are present in a folder named SaveNotes. You should navigate to your own directory structure when called to later.

Steps to install the application in your Firefox OS Simulator should be familiar to you now. Simply launch the Firefox OS Simulator in your Firefox Browser. From the Dashboard, click on the Add Directory button and point it to the manifest.webapp file for the SaveNotes application. On successful validation, the application will be installed and it will come up in your OS Simulator. For sample screenshots, refer to the section at the beginning of this blog post for Episode 6 in Action.

Debugging Local Storage

If you recollect Episode 3 : Working with the OS Simulator, we had covered how to Connect the running Firefox OS application running in the simulator and debug the execution, including placing break points.

You can debug the current state of the localStorage object in the same manner. To try that out, go to the Firefox OS Simulator Dashboard in your Firefox Browser and use the Connect button for the SaveNotes application. This will connect to the running instance of the SaveNotes application and the Console window will be visible.

ep6-screen6

In the Console, go ahead and type localStorage as shown above and click Enter. This will show the current state of the localStorage object as shown below. For e.g. I had a few notes saved and hence you see that list. I suggest you give it a try by inspecting the localStorage without any items, then add a few items and then inspect the value again. You will be able to see the list of items that you have added.

ep6-screen7

You can even try out the different methods of the localStorage API. For e.g. in the screenshot below, I have tried out localStorage.length that returns me a value of 3, since I have 3 notes saved. Similarly, I have also tried out localStorage.key(0) that returns me the value of the key at index 0.

ep6-screen8

Next Steps

I encourage you to enhance the current application by giving the ability to delete individual notes. You could even opt for a more array-like representation of the data that you put in localStorage. How about providing a search feature on the View Notes screen? Go for it.

If you would like to learn more about Local Storage, I strongly suggest for you for try out the following tutorial : Dive Into HTML5 : Storage. Alternately, you can also look at a couple of my blog posts: Storage 101 and More on Local Storage.

Coming up Next

The next episodes will either cover another HTML5 API for persistence called IndexedDB. This is more powerful compared to the LocalStorage and gives you SQL-like ability to work with your databases. Or I might just jump into the various Device APIs. Stay tuned.

Till the next time, stay tuned and give me feedback.

Complete Firefox OS Tutorial

Feedback

I would love to hear your feedback on the series so far. Do put your feedback in the comments. If you are facing issues, use the comments to let me know about it, I will do my best to answer your queries. And by putting in your issues within this thread itself, it will help build collective knowledge that could help other readers.


Firefox OS

Advertisements

13 thoughts on “Firefox OS Tutorial : Episode 6 : Enabling Storage

  1. Hi,
    I am a question referring to localStorage: if I remove an app (in Fx OS mobile or simulator) which uses localStorage data, this localStorage data will be deleted too?
    I ask this because I have an app which stores an image list in an array. And some elements from this array are put into the localStorage. But if in the future I remove my app in order to install a newer version and in that version I will change some images there may be problems if the localStorage data will not be deleted when removing the previous version.

    1. I believe the Local Storage data is specific to your application and it should get deleted when you uninstall your application, or if the user chooses to clear it.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s