Download presentation
Presentation is loading. Please wait.
1
CIS 136 Building Mobile Apps
Storage CIS 136 Building Mobile Apps
2
Storage Options
3
Storage Options Many storage API’s Local Storage & session storage
Simple storage technique using key/value pairs WebSQL (android, blackberry, iOS) full-featured database tables accessed via SQL queries IndexedDB (windows, blackberry) more features than LocalStorage but fewer than WebSQL Plug-in Based File Plug-In - allows you to cache data on the local file system Downloader Plug-In- Downloads files to persistent Storage SQLLite Plug-In- more storage and more flexibility than the standard Web SQL database
4
Local Storage
5
Local/Session Storage
most basic storage option available allows you to store up to 5MB of data Unreliable Data can get wiped out use it where data loss is not an issue never use it to store sensitive data since it can be easily accessed
6
Local Storage Reasons we might want to store some data locally:
The application is completely self contained and there is no interaction with other users, so all data can be stored locally Need to store data locally for some specific functionality like a “Remember Me” feature Skip unnecessary calls to a server by storing preference settings locally Skip unnecessary calls to a server by caching other data locally Sync online and offline data so that the user can continue using the application even when they are offline Evernote /Facebook
7
Local Storage a simple key-value system, using setters and getters
localStorage.setItem('key', ‘value'); var someSetting = localStorage.getItem(‘key'); can only store strings to store an object or array, must convert it to a JSON string var myConvertedArray = JSON.stringify(array); to retrieve it later, decode JSON string back into an array or object var myDecodedArray = JSON.parse(myConvertedArray);
8
Local Storage vs Session Storage
Permanent – localStorage() method Data is saved even when app is closed Temporary – sessionStorage() method Data is not saved when app is closed
9
Methods Works off of key/value pairs
Set an item - Assigns a keyed item's value window.localStorage.setItem("key", "value"); Get a key - Returns the name of the key at the specified position var keyName = window.localStorage.key(0); Get an item - Returns the item identified by the specified key var value = window.localStorage.getItem("key"); Remove an item - Removes the item identified by the specified key Window.localStorage.removeItem("key"); Clear - Removes all of the key/value pairs Window.localStorage.clear();
10
<script> // Wait for device API libraries to load $(document).on("deviceready", onDeviceReady); //uses named function // device APIs are available function onDeviceReady() { window.localStorage.setItem(“hobby", “sailing"); var keyname = window.localStorage.key(0); // keyname is now = “hobby" var value = window.localStorage.getItem(“hobby"); // value is now = “sailing“ var value2 = window.localStorage.getItem(keyname); // value is now = “sailing" window.localStorage.removeItem(“hobby"); window.localStorage.setItem(“hobby2", “riding"); window.localStorage.clear(); // localStorage is now empty } </script>
11
IndexedDB
12
IndexedDB IndexedDB combines the strengths of the LocalStorage and WebSQL supports the storage of structured data rather than key/value pairs The basic pattern that IndexedDB encourages is the following: Create/Open a database Create/Open an object store in the database (similar to a table) Start a transaction and make a request to do some database operation, like adding or retrieving data. Wait for the operation to complete by listening for the event Do something with the results (which can be found on the request object).
13
Creating/Opening a Database
When you open a database, you get a DB object, which provides error and success events, and properties such as result, error and readyState var db; var dbName = 'myDB'; var databaseVersion = 1 var openRequest = window.indexedDB.open(dbName [,databaseVersion]); openRequest.onerror = function (e) { console.log(e.target.errorCode); }; openRequest.onsuccess = function (event) { // Existing Database is open and initialized db = event.target.result; … NOTE: The database is created if a database with the specified name does not exist. Only a single version of a database can exist at a time. When a database is first created, its initial version is zero
14
New database When you create a new database or increase the version number of an existing database (by specifying a higher version number than you did previously, the onupgradeneeded event will be triggered
15
Creating a new object store
function createObjectStore() { var openRequest = window.indexedDB.open(dbName, 2); openRequest.onerror = function(e) console.log("Database error: " + e.target.errorCode); }; openRequest.onupgradeneeded = function (evt) db = event.target.result; var employeeStore = db.createObjectStore("employees", {keyPath: "id"}); }
16
Indexes Can retrieve records in an object store using its key or indexed fields can have one or more indexes, and they can either be unique or non- unique function createIndex() { var openRequest = window.indexedDB.open(dbName, 2); openRequest.onsuccess = function(event) { db = event.target.result; }; openRequest.onupgradeneeded = function (evt) { var employeeStore = db.createObjectStore("employees", {keyPath: "id"}); employeeStore.createIndex(" Index", " ", { unique: true }); employeeStore.createIndex("zipCodeIndex", "zip_code", { unique: false }) }
17
Transactions Used to perform reading and writing operations on an object store Three modes:
18
Creating records Data is a string literal array
var empData = [ { id: " ", name: "Bill", zip: 35022, }, { id: " ", name: “Dave", zip: 32034, }, ]; Store values in the newly created objectStore. var employeeStore = db.transaction(“employees“,”readwrite").objectStore(“employees"); empData.forEach(function(empRec) { employeeObjectStore.add(empRec); }
19
Retrieve a specific record using key
function fetchEmployee() { var result = document.getElementById("result"); result.innerHTML = ""; if (db != null) { var txn = db.transaction(["employees“]) var objStore = txn. objectStore("employees"); var request = objStore.get("E3") request.onsuccess = function(event) var employee = request.result; if (employee == null) { result.value = "employee not found"; } else { var jsonStr = JSON.stringify(employee.id); result.innerHTML = jsonStr;
20
Delete A Database function deleteDatabase() { var deleteDbRequest = window.indexedDB.deleteDatabase(dbName); deleteDbRequest.onsuccess = function (event) { // database deleted successfully }; deleteDbRequest.onerror = function (e) { console.log("Database error: " + e.target.errorCode); }
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.