Date post: | 16-Apr-2017 |
Category: |
Technology |
Upload: | ivano-malavolta |
View: | 308 times |
Download: | 1 times |
Local storage and file system access
There are 4 ways to store data locally in Cordova:
• Web storage
• Local Storage
• Session Storage
• WebSQL
• Indexed DB
• File System AccessNot considered in this course
Web Storage
LocalStorage
stores data in key/value pairs
persists across browser sessions
SessionStorage
stores data in key/value pairs
data is erased when a browser session ends
WebSQL
relational DB
support for tables creation, insert, update, …
transactional
persists across browser sessions
WebSQL
It provides you a structured SQL relational database
You have to setup a DB schema
You can then perform classical SQL queries
tx.executeSql(‘SELECT * FROM User’, [],function(tx, result) {
// callback code});
IndexedDB
• It combines Web Storage and WebSQL
• You can save data as key/value pairs
• You can define multiple DBs
• Good Performance– data is indexed
– Asynchronous à it does not block the UI
You can see a store as a big SQL table with only key/value pairs
à you don’t need to define a schema upfront
File System
• you can access files locally to your app
• supports main FS operation– creation, move, delete, rename, etc.
• it is not transactional
• persists across browser sessions
Web Storage
It is based on a single persistent object calledlocalStorage
You can set values by callingwindow.localStorage.setItem(“name”, “Ivano”);
You can get values back by callingvar name = window.localStorage.getItem(“name”);
Supported Methods
.key(0)Returns the name of the key at the position specified
.getItem(“key”)Returns the item identified by it's key
.setItem(“key”, “value”)Saves and item at the key provided
.removeItem(“key”)Removes the item identified by it's key
.clear()Removes all the key-value pairs
Complex Objects
Current implementations support only string-to-string mappings
à you can store only strings
à keys can be only strings
You can use JSON serialization if you need to store complex data structures
Example of JSON Serialization
// simple class declarationfunction Person(name, surname) {
this.name = name;this.surname = surname;
}
// object creationvar user = new Person(‘Ivano’, ‘Malavolta’);
// object serializationwindow.localStorage.setItem(“user”, JSON.stringify(user));
// object retrievalvar current =
JSON.parse(window.localStorage.getItem(“user”));
Checking Existence
You can simply check if the needed element is == null
if (window.localStorage.getItem(“user”)) {
// there is an object in user} else {
// the user key does not have any value
}
Selecting elements
In this case you have to manually iterate on elements
var users = [...]; // array of Person objectswindow.localStorage.setItem(“users”,
JSON.stringify(users));
var allUsers = JSON.parse(window.localStorage.getItem(“users”));
var ivanos = []; for(var i=0; i<allUsers.length; i++) {
if(allUsers[i].name == ‘Ivano’) ivanos.push(allUsers[i]);
}
Session Storage
Session Storage provides the same interface as Local Storage
à you can call the same methods
but
Session Storage is cleared between app launches
WebSQL
It provides you a structured SQL relational database
You have to setup a DB schema
You can then perform classical SQL queries
tx.executeSql("SELECT * FROM User“, [],
function(tx, result) {// callback code
});
Opening a DB
Done via a dedicated function
var db =openDatabase(‘Test', ‘1.0', ‘Test DB', 100000);
It creates a new SQLite DB and returns a new Database object
The Database object will be used to manipulate the data
Opening a DB: syntax
openDatabase(name, version, displayname, size);
namethe name of the DB
versionthe version of the DB
displaynamethe display name of the DB
sizethe size of the DB in bytes
Database
It allows to manipulate the data via 2 methods:
changeVersion
atomically verify the version number and change it
db.changeVersion("1.0", "1.1");
transaction
performs a DB transaction
Transactions
It allow you to execute SQL statements against the DB
db.transaction(queries, error, success);
3 functions as parameters:
queries : contains the queries to be performed
error : executed if the transaction results in an error
success : executed if the transaction terminates correctly
executeSql
It is the method that performs a SQL statement
The user can build up a database transaction by calling the executeSql method multiple times
function populateDB(tx) {tx.executeSql('DROP TABLE IF EXISTS USER');tx.executeSql('CREATE TABLE IF NOT EXISTS USER (id
unique, name, surname)');
tx.executeSql('INSERT INTO USER(id, name, surname) VALUES (1, ?, ?)‘, [“Ivano“, “Malavolta“], success, error);
}
Result Sets
When the executeSql method is called, it will invoke it's callback with a SQLResultSet parameter
It has 3 properties:
insertId
the ID of the row that has been inserted
rowsAffected
the number of rows changed by the SQL statement
rows
the data returned from a SQL select statement
rows is an object of type SQLResultSetList
Results Sets Example
...
tx.executeSql('INSERT INTO USER(id, name,surname) VALUES (5, ?, ?)‘, [“Ivano“, “Malavolta“], success, error);
}
function success(tx, results) {
var affected = results.rowsAffected(); // 1
}
function error(err) {
// code for managing the error
}
Result Set Lists
It contains the data returned from a SQL Select statement
length
the number of rows returned by the SQL query
item(index)
returns the row at the specified index represented by a JavaScript object
Result Set List Example
...
tx.executeSql(‘SELECT * FROM USER‘, [], success, error);}
function success(tx, results) {var size = results.rows.length;for (var i=0; i<size; i++){
console.log(results.rows.item(i).name);}
}
Errors
It contains information about an occurred error
code
A predefined error code
es. UNKNOWN_ERR,
DATABASE_ERR,
TOO_LARGE_ERR,
QUOTA_ERR,
TIMEOUT_ERR,
SYNTAX_ERR
messageA description of the error
error not considered by any other error codes
internal error of the database
the result set is too large
the db now exceeds the storage space of the app
• the statement is not sintactically correct• the number of parameters does not match with
placeholders
no reasonable time to get the lock for the transition
Error Code Example
...tx.executeSql(‘SELECT * FROM USER‘,[], success, error);
}
function error(err) {console.log(err.code);
}
Considerations
You will likely use more than one API in combination
à Use the right API for the right job
Web Storage
• it is not transactional à race conditions
• very simple API, no schema
• only String data à performance issues for complex data due to JSON serialization
• session storage will be cleared after the app is closed
• limited quota
Considerations
WebSQL
SQL-based à fast and efficient
transactional àmore robust
asynchronous à does not block the UI
rigid data structure à data integrity vs agility
limited quota
Considerations
IndexedDB
simple data model à easy to use
transactional àmore robust
asynchronous à does not block the UI
good search performance à indexed data
data is unstructured à integrity problems
limited quota
not fully supported by every platform (e.g., iOS)
Considerations
File System
asynchronous à does not block the UI
not transactional
indexing and search are not built-in à you have to implement your lookup functions
unlimited quota à useful for images, videos, documents, etc.
About quotas...
Local Storage
~ 10Mb
Session Storage
~ 10Mb
WebSQL
~ 50-80Mb
(depends on the device)
Indexed DB
~ 50-80Mb
(depends on the device)
File system
unlimited
Native DB
unlimited
LAB
Extend the app of the previous labs so that users can:
1. save a specific product as favorite via local storage
2. define a dedicated “Favorites” view of the app;
ContactIvano Malavolta |
Gran Sasso Science Institute
iivanoo
www.ivanomalavolta.com