Money Book(M) Sample Overview

The Money Book sample application demonstrates how you can save and load data in a database storage.

The following figure illustrates the main screens of the Money Book.

Figure: Money Book screens

Money Book screens

The application opens with the result screen, which displays all added records.

To add a record:

  1. Go to the input screen by clicking Back on the result screen.
  2. Enter the name and price of the item to the textbox, and click Submit.

To remove a record, press the ID number (the first field) of the record to remove on the result screen. To remove all records, click Clear.

Source Files

You can create and view the sample application project, including the source files, in the IDE.

Table: Source files
File name Description
config.xml This file contains the application information for the platform to install and launch the application, including the view mode and the icon to be used in the device menu.
css/style.css This file contains the CSS styling for the application UI.
index.html This is a starting file from which the application starts loading. It contains the layout of the application screens.
js/app.js This file contains the code for handling the main functionality of the application.
js/page.js This file contains the code for handling the page navigation functionality.

Implementation

Application Layout

To create the application layout, add the page elements to the page controller. The first added page becomes the main page.

/* app.js */
/* function setDefaultVariables() */
/* Add all pages to the page controller */
for (i = 0; i < pageList.length; i++)
{
   pageController.addPage(pageList[i]);
}

Basic Operations

The entry point for the application is the js/app.js module, and the page module is required to run the application. Include both .js files.

<!--index.html-->
<script src="js/page.js"></script>
<script src="js/app.js"></script>

The js/app.js module registers callbacks for user events, such as the Back key or bezel rotation:

/* js/app.js */
function setDefaultEvents() 
{
   document.addEventListener("tizenhwkey", keyEventHandler);
   btnInputBack.addEventListener("click", function()
   {
      loadDataView(db);
      pageController.movePage("page-result");
   });
   btnSubmit.addEventListener("click", function()
   {
      var txtItem = document.querySelector("#input-item"),
          txtPrice = document.querySelector("#input-price");

      if (!txtItem.value && !txtPrice.value)
      {
         showPopup("Item name and Price data are needed.", "OK");
      }
      else
      {
         showPopup("Do you want add new data?", "OKCancel",
         {
            cbOK: submitNewRecord,
            cbCancel: null
         });
      }
   });

   btnInputPage.addEventListener("click", function()
   {
      pageController.movePage("page-input");
   });
   btnClear.addEventListener("click", function()
   {
      showPopup("Do you want to delete all data?", "OKCancel",
      {
         cbOK: function()
         {
            var objResult = document.querySelector("#detail-result");

            emptyElement(objResult);
            deleteDataAll(db);
         },
         cbCancel: null
      });
   });
}

Database Manipulation

When the application starts, it attempts to open the database using the WebSQL API or Indexed Database API:

  1. Store the information about which API is supported by the device to access the database.

    /* app.js */
    /* function openDB(successCb) */
    if (window.indexedDB)
    {
       dbType = "IDB";
    
       request = indexedDB.open(DB_NAME, DB_VERSION);
       request.onerror = function(e)
       {
          alert("Please allow this application to use Indexed DB");
       };
       request.onsuccess = function(e)
       {
          db = request.result;
          if (successCb)
          {
             successCb(db);
          }
       };
       /*
          Set a callback function When the Indexed DB is created first,
          or upgrade is needed
       */
       request.onupgradeneeded = function(e)
       {
          db = e.target.result;
          createTable(db);
       };
    }
    else if (window.openDatabase)
    {
       dbType = "SQL";
    
       db = openDatabase(DB_NAME, DB_VERSION, DB_DISPLAY_NAME, DB_SIZE);
       createTable(db);
    
       if (successCb)
       {
          successCb(db);
       }
    }
    
  2. After the database is opened, the application creates a table to the database, if none exists:

    /* app.js */
    /* function createTable(db) */
    if (dbType === "IDB")
    {
       if (db.objectStoreNames.contains(DB_TABLE_NAME))
       {
          db.deleteObjectStore(DB_TABLE_NAME);
       }
    
       idbObjectStore = db.createObjectStore(DB_TABLE_NAME, 
       {
          keyPath: "id",
          autoIncrement: true
       });
    }
    else if (dbType === "SQL")
    {
       db.transaction(function(t)
       {
          t.executeSql("CREATE TABLE IF NOT EXISTS " + DB_TABLE_NAME + 
                       " (id INTEGER PRIMARY KEY, item TEXT, price INTEGER, insertday DATETIME)", []);
       });
    }
    
  3. To manage the data:
    • To get data from the database, use the Cursor object of the Indexed Database API or the SELECT SQL query:

      /* app.js */
      /* function loadDataView(db) */
      if (dbType === "IDB")
      {
         idbObjectStore = db.transaction(DB_TABLE_NAME, "readonly").objectStore(DB_TABLE_NAME);
         idbObjectStore.openCursor().onsuccess = function(e)
         {
            var cursor = e.target.result;
      
            if (cursor)
            {
               resultBuffer.push(cursor.value);
               cursor.continue();
            }
            else
            {
               showDataView(resultBuffer);
      
               return resultBuffer;
            }
         };
      }
      else if (dbType === "SQL")
      {
         db.transaction(function(t)
         {
            t.executeSql("SELECT * FROM " + DB_TABLE_NAME, [], function(t, r)
            {
               var resultBuffer = [],
                   i;
      
               for (i = 0; i < r.rows.length; i++)
               {
                  resultBuffer.push(
                  {
                     id: r.rows.item(i).id || 0,
                     item: r.rows.item(i).item || "",
                     price: r.rows.item(i).price || 0,
                     insertday: r.rows.item(i).insertday || ""
                  });
               }
      
               showDataView(resultBuffer);
      
               return resultBuffer;
            }
         });
      }
      
    • To insert and delete data, use the put() and delete() methods or the INSERT and DELETE SQL queries:

      /* app.js */
      /* function insertData(db, data) */
      if (dbType === "IDB")
      {
         idbObjectStore = db.transaction(DB_TABLE_NAME, "readwrite").objectStore(DB_TABLE_NAME);
         idbObjectStore.put(data);
      }
      else if (dbType === "SQL")
      {
         db.transaction(function(t)
         {
            var dayString;
      
            dayString = getDateTimeString();
            t.executeSql("INSERT INTO " + DB_TABLE_NAME +
                         " (item, price, insertday) VALUES (?, ?, ?)", [data.item, data.price, dayString]);
         });
      }
      
      /* app.js */
      /* function deleteData(db, data) */
      if (dbType === "IDB")
      {
         idbObjectStore = db.transaction(DB_TABLE_NAME, "readwrite").objectStore(DB_TABLE_NAME);
         idbObjectStore.delete(data.id);
      }
      else if (dbType === "SQL")
      {
         db.transaction(function(t)
         {
            t.executeSql("DELETE FROM " + DB_TABLE_NAME + " WHERE id = ?", [data.id]);
         });
      }