+ All Categories
Home > Technology > Local Storage

Local Storage

Date post: 12-May-2015
Category:
Upload: gran-sasso-science-institute
View: 1,000 times
Download: 1 times
Share this document with a friend
Description:
Mobile applications Development - Lecture 13 Local/Session Storage WebSQL IndexedDB File System Access This presentation has been developed in the context of the Mobile Applications Development course at the Computer Science Department of the University of L’Aquila (Italy). http://www.di.univaq.it/malavolta
Popular Tags:
65
Local Storage Ivano Malavolta Ivano Malavolta [email protected] http://www.di.univaq.it/malavolta
Transcript
Page 1: Local Storage

Local Storage

Ivano MalavoltaIvano Malavolta

[email protected]

http://www.di.univaq.it/malavolta

Page 2: Local Storage

Roadmap

• Introduction

• Web Storage• Web Storage

• WebSQL

• IndexedDB

• File System Access

• Final Considerations• Final Considerations

Page 3: Local Storage

Introduction

There are 4 ways to store data locally

• Web Web Web Web storagestoragestoragestorage– LocalLocalLocalLocal StorageStorageStorageStorage

– SessionSessionSessionSession StorageStorageStorageStorage

• WebSQLWebSQLWebSQLWebSQL

• IndexedIndexedIndexedIndexed DBDBDBDB

• File System AccessFile System AccessFile System AccessFile System Access

Page 4: Local Storage

Web Storage

LocalStorageLocalStorageLocalStorageLocalStorage

stores data in key/value pairsstores data in key/value pairs

persists across browser sessions

SessionStorageSessionStorageSessionStorageSessionStorage

stores data in key/value pairsstores data in key/value pairs

data is erased when a browser session ends

Page 5: Local Storage

Introduction

WebSQLWebSQLWebSQLWebSQL DatabaseDatabaseDatabaseDatabase

relational DBrelational DB

support for tables creation, insert, update, …

transactional

persists across browser sessions

Its evolution is called IndexedDBIndexedDBIndexedDBIndexedDB, but it is actuallynot supported by most mobile browsers

Page 6: Local Storage

Introduction

File System AccessFile System AccessFile System AccessFile System Access

you can access files locally to your appyou can access files locally to your app

supports main FS operations– files creation, move, delete, rename, creation, etc.

it is not transactional

persists across browser sessions

Page 7: Local Storage

Introduction

Mobile browsers compatibility matrix

Page 8: Local Storage

Roadmap

• Introduction

• Web Storage• Web Storage

• WebSQL

• IndexedDB

• File System Access

• Final Considerations• Final Considerations

Page 9: Local Storage

Web Storage

It is based on a single persistent object calledlocalStoragelocalStorage

You can set values by callingwindow.localStorage.setItem(“name”, “Ivano”);

You can get values back by callingvar name = window.localStorage.getItem(“name”);

Page 10: Local Storage

Supported Methods

localStorage.key(0)

Returns the name of the key at the position specifiedReturns 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(“hey”)

Removes the item identified by it's key

clear()

Removes all of the key value pairs

Page 11: Local Storage

Complex Objects

Current implementations support only string-to-stringmappingsmappings

� you can store onlyonlyonlyonly stringsstringsstringsstrings

� keys can be onlyonlyonlyonly stringsstringsstringsstrings

You can use JSON JSON JSON JSON serializationserializationserializationserialization if you need to storecomplex data structures

Page 12: Local Storage

Example of JSON Serialization

// simple class declaration

function Person(name, surname) {

this.name = name;this.name = name;

this.surname = surname;

}

// object creation

var user = new Person(‘Ivano’, ‘Malavolta’);

// object serialization

window.localStorage.setItem(“user”, JSON.stringify(user)); window.localStorage.setItem(“user”, JSON.stringify(user));

// object retrieval

var current = JSON.parse(window.localStorage.getItem(“user”));

Page 13: Local Storage

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// the user key does not have any value

}

Page 14: Local Storage

Selecting elements

In this case you have to manually iterate on elements

var users = [...]; // array of Person objects

window.localStorage.setItem(“users”,

JSON.stringify(users));

var allUsers =

JSON.parse(window.localStorage.getItem(“users”));

var ivanos = []; var ivanos = [];

for(var i=0; i<allUsers.length; i++) {

if(allUsers[i].name == ‘Ivano’)

ivanos.push(allUsers[i]);

}

Page 15: Local Storage

Counting Elements

Also in this case, we have to do it manually

var usersNumber =

JSON.parse(window.localStorage.getItem(“users“)).length;

Page 16: Local Storage

Session Storage

Session Storage provides the same interface as Local StorageStorage

� you can call the same methods

but

Session Storage is cleared between app launchesSession Storage is cleared between app launchesSession Storage is cleared between app launchesSession Storage is cleared between app launches

Page 17: Local Storage

Roadmap

• Introduction

• Web Storage• Web Storage

• WebSQL

• IndexedDB

• File System Access

• Final Considerations• Final Considerations

Page 18: Local Storage

WebSQL

It provides you a structured SQL relational databaseSQL relational databaseSQL relational databaseSQL relational database

You have to setup a DB schemaDB schemaDB schemaDB schema

You can then perform classicalclassicalclassicalclassical SQL SQL SQL SQL queriesqueriesqueriesqueries

tx.executeSql("SELECT * FROM User“, [],tx.executeSql("SELECT * FROM User“, [],

function(tx, result) {

// callback code

});

Page 19: Local Storage

Opening a DB

Done via a dedicated function

var db =

openDatabase(‘Test', ‘1.0', ‘Test DB', 100000);

It creates a new SQLLite DB and returns a newDatabaseDatabaseDatabaseDatabase objectDatabaseDatabaseDatabaseDatabase object

The Database object will be used to manipulate the data

Page 20: Local Storage

Opening a DB: syntax

openDatabase(name, version, displayname, size);

DB DB DB DB namenamenamenamethe name of the DB

DB DB DB DB versionversionversionversionthe version of the DB

DB Display DB Display DB Display DB Display namenamenamenamethe display name of the DB

DB DB DB DB SizeSizeSizeSizethe size of the DB in bytes

Page 21: Local Storage

Database

It allows to manipulate the data via 2 methods:

changeVersionchangeVersionchangeVersionchangeVersion

atomically verify the version number and change it

db.changeVersion("1.0", "1.1");

transactiontransactiontransactiontransaction

performs a DB transaction

Page 22: Local Storage

Transactions

It allow you to execute SQL statements against the DB

db.transaction(queries, error, success);

3 callback functions:

queriesqueriesqueriesqueries : contains the queries to be performedqueriesqueriesqueriesqueries : contains the queries to be performed

errorerrorerrorerror : executed if the transaction results in an error

successsuccesssuccesssuccess : executed if the transaction terminates correctly

Page 23: Local Storage

Transaction Example

http://bit.ly/JlUJde

Page 24: Local Storage

executeSql

It is the method that performs a SQL statement

The user can build up a database transaction by calling the executeSqlexecuteSqlexecuteSqlexecuteSql method multiple times

function populateDB(tx) {

tx.executeSql('DROP TABLE IF EXISTS USER');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);

}

Page 25: Local Storage

Result Sets

When the executeSql method is called, it will invoke it's callback with a SQLResultSetSQLResultSetSQLResultSetSQLResultSet parameterparameterparameterparameter

It has 3 properties:

insertIdinsertIdinsertIdinsertId

the ID of the row that has been inserted

rowsAffectedrowsAffectedrowsAffectedrowsAffected

the number of rows changed by the SQL statement

rowsrowsrowsrows

the data returned from a SQL select statement

rows is an object of type SQLResultSetList

Page 26: Local Storage

Results Sets Example

...

tx.executeSql('INSERT INTO USER(id, name,surname) tx.executeSql('INSERT INTO USER(id, name,surname)

VALUES (1, ?, ?)‘, [“Ivano“, “Malavolta“],

success, error);

}

function success(tx, results) {

var affected = results.rowsAffected(); // 1

}}

function error(err) {

// code for managing the error

}

Page 27: Local Storage

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)item(index)

returns the row at the specified index represented by a JavaScript object

Page 28: Local Storage

Result Set List Example

...

tx.executeSql(‘SELECT * FROM USER‘, [], tx.executeSql(‘SELECT * FROM USER‘, [],

success, error);

}

function success(tx, results) {

var size = results.rows.length;

for (var i=0; i<size; i++){for (var i=0; i<size; i++){

console.log(results.rows.item(i).name);

}

}

Page 29: Local Storage

Errors

It contains information about an occurred error

codecodecodecode

A predefined error code

es. UNKNOWN_ERR, DATABASE_ERR, TOO_LARGE_ERR, QUOTA_ERR, SYNTAX_ERR, TIMEOUT_ERR

messagemessagemessagemessage

A description of the error

Page 30: Local Storage

Error Code Example

...

tx.executeSql(‘SELECT * FROM USER‘,[], tx.executeSql(‘SELECT * FROM USER‘,[],

success, error);

}

function error(err) {

console.log(err.code);console.log(err.code);

}

Page 31: Local Storage

Roadmap

• Introduction

• Web Storage• Web Storage

• WebSQL

• IndexedDB

• File System Access

• Final Considerations• Final Considerations

Page 32: Local Storage

Indexed DB

It tries to combine Web Storage and WebSQL

You can save data as key/key/key/key/valuevaluevaluevalue pairspairspairspairs

You can define multiple multiple multiple multiple DBsDBsDBsDBs

GoodGoodGoodGood PerformancePerformancePerformancePerformanceGoodGoodGoodGood PerformancePerformancePerformancePerformance

data is indexed

asynchronous � it does not block the UI

Page 33: Local Storage

Indexed DB

An Indexed DB is a collection of object storesobject storesobject storesobject stores

You can drop objects into the stores

You can see stores as a big SQL table with onlykey/key/key/key/valuevaluevaluevalue pairspairspairspairs

� youyouyouyou don’t don’t don’t don’t needneedneedneed totototo definedefinedefinedefine a schema a schema a schema a schema upfrontupfrontupfrontupfront

Page 34: Local Storage

Roadmap

• Introduction

• Web Storage• Web Storage

• WebSQL

• IndexedDB

• File System Access

• Final Considerations• Final Considerations

Page 35: Local Storage

File System Access

It allows you to read, write and navigate read, write and navigate read, write and navigate read, write and navigate file system hierarchieshierarchies

It is fundamental for managing and storing large files large files large files large files and binary content on the clientand binary content on the clientand binary content on the clientand binary content on the client----sidesidesideside

Page 36: Local Storage

File System Access Workflow

1. RequestRequestRequestRequest file system file system file system file system accessaccessaccessaccess

– persistent or temporary file system– persistent or temporary file system

2. then you can perform CRUD operations for both files and folders:

– CCCCreate

– RRRRead– RRRRead

– UUUUpdate

– DDDDelete

Page 37: Local Storage

Request File System

requestFileSystem(type, size, successCb, [errorCb])

typetypetypetypeLocalFileSystem.TEMPORARYLocalFileSystem .PERSISTENT

sizesizesizesizesize in bytes the app will require for storage.

successCbsuccessCbsuccessCbsuccessCbsuccess callback, its argument is a FileSystem object

ErrorCbErrorCbErrorCbErrorCberror callback, its argument is a FileError object

Page 38: Local Storage

Temporary VS Persistent

TemporaryTemporaryTemporaryTemporary

the files stored by the app can be deleted at the the files stored by the app can be deleted at the browser’s discretion

� no guarantee of persistence

PersistentPersistentPersistentPersistentPersistentPersistentPersistentPersistent

cannot be deleted by the browser withoutauthorization by the app

Page 39: Local Storage

Local File System Example

window.requestFileSystem(

LocalFileSystem.PERSISTENT, LocalFileSystem.PERSISTENT,

0,

onSuccess,

onError);

function onSuccess(fileSystem) {

console.log(fileSystem.name);console.log(fileSystem.name);

}

Page 40: Local Storage

File System

The FileSystem object has 2 properties:

namenamenamenamethe name of the file systemit is unique across the list of exposed file systems

rootrootrootrootrootrootrootrootthe DirectoryEntryDirectoryEntryDirectoryEntryDirectoryEntry object representing the rootfolder of the file system

Page 41: Local Storage

Resolving a File URI

resolveLocalFileSystemURIresolveLocalFileSystemURIresolveLocalFileSystemURIresolveLocalFileSystemURI

retrieve a DirectoryEntryDirectoryEntryDirectoryEntryDirectoryEntry or FileEntryFileEntryFileEntryFileEntry using a URIretrieve a DirectoryEntryDirectoryEntryDirectoryEntryDirectoryEntry or FileEntryFileEntryFileEntryFileEntry using a URI

window.resolveLocalFileSystemURI(

"file:///userImg.png", onSuccess, onError);

function onSuccess(fileEntry) {

console.log(fileEntry.name);

}

Page 42: Local Storage

Entities

FileEntry

DirectoryEntryThe real objects

DirectoryEntry

File

FileReader

The real objects

Descriptor

FileReader

FileWriter

DirectoryReader

Writing & Reading objects

Page 43: Local Storage

File Entry

It represents a filefilefilefile on a file system

isFileisFileisFileisFile (boolean)Always true

isDirectoryisDirectoryisDirectoryisDirectory (boolean)Always false

name name name name (DOMString)the name of the FileEntry, excluding the path

fullPathfullPathfullPathfullPath (DOMString) the full absolute path from the root

Page 44: Local Storage

File Entry Methods

getMetadatagetMetadatagetMetadatagetMetadata(success, fail)(success, fail)(success, fail)(success, fail)Look up metadata about a fileLook up metadata about a file

moveTomoveTomoveTomoveTo((((parentEntryparentEntryparentEntryparentEntry, , , , newNamenewNamenewNamenewName, success, fail), success, fail), success, fail), success, fail)Move a file to a different location on the file system

copyTocopyTocopyTocopyTo((((parentEntryparentEntryparentEntryparentEntry, , , , newNamenewNamenewNamenewName, success, fail), success, fail), success, fail), success, fail)copyTocopyTocopyTocopyTo((((parentEntryparentEntryparentEntryparentEntry, , , , newNamenewNamenewNamenewName, success, fail), success, fail), success, fail), success, fail)Copy a file to a different location on the file system

toURItoURItoURItoURI()()()()Return a URI that can be used to locate a file

Page 45: Local Storage

File Entry Methods

remove(success, fail)remove(success, fail)remove(success, fail)remove(success, fail)Delete a fileDelete a file

getParentgetParentgetParentgetParent(success, fail)(success, fail)(success, fail)(success, fail)Look up the parent directory

createWritercreateWritercreateWritercreateWriter(success, fail)(success, fail)(success, fail)(success, fail)Creates a FileWriter object that can be used to write Creates a FileWriter object that can be used to write to a file

file(success, fail)file(success, fail)file(success, fail)file(success, fail)Creates a File object containing file properties

Page 46: Local Storage

File

It contains attributes of a single file

name name name name (DOMString)The name of the file

fullPathfullPathfullPathfullPath (DOMString)The full path of the file including the file name

type type type type (DOMString)The mime type of the fileThe mime type of the file

lastModifiedDatelastModifiedDatelastModifiedDatelastModifiedDate (Date)The last time the file was modified

size size size size (long) The size of the file in bytes

Page 47: Local Storage

Directory Entry

It represents a directorydirectorydirectorydirectory on a file system

It has the same properties of FileEntry

Page 48: Local Storage

Directory Entry Methods

getMetadatagetMetadatagetMetadatagetMetadata(success, fail)(success, fail)(success, fail)(success, fail)Look up metadata about a directoryLook up metadata about a directory

moveTomoveTomoveTomoveTo((((parentEntryparentEntryparentEntryparentEntry, , , , newNamenewNamenewNamenewName, success, fail), success, fail), success, fail), success, fail)Move a directory to a different location on the file system

copyTocopyTocopyTocopyTo((((parentEntryparentEntryparentEntryparentEntry, , , , newNamenewNamenewNamenewName, success, fail), success, fail), success, fail), success, fail)Copy a directory to a different location on the file systemCopy a directory to a different location on the file system

toURItoURItoURItoURI()()()()Return a URI that can be used to locate a directory

Page 49: Local Storage

Directory Entry Methods

getParentgetParentgetParentgetParent(success, fail)(success, fail)(success, fail)(success, fail)getParentgetParentgetParentgetParent(success, fail)(success, fail)(success, fail)(success, fail)Look up the parent directory

createReadercreateReadercreateReadercreateReader()()()()Creates a DirectoryReader object that can be used to read a directory

getDirectorygetDirectorygetDirectorygetDirectory(path, options, success, fail)(path, options, success, fail)(path, options, success, fail)(path, options, success, fail)getDirectorygetDirectorygetDirectorygetDirectory(path, options, success, fail)(path, options, success, fail)(path, options, success, fail)(path, options, success, fail)Create or look up a directoryoptions:

create � (true | false)exclusive � (true | false)

Page 50: Local Storage

Directory Entry Methods

getFilegetFilegetFilegetFile(path, options, success, fail)(path, options, success, fail)(path, options, success, fail)(path, options, success, fail)

Create or look up a file within the directoryCreate or look up a file within the directory

options:

create � (true | false)

exclusive � (true | false)

removeRecursivelyremoveRecursivelyremoveRecursivelyremoveRecursively(success, fail)(success, fail)(success, fail)(success, fail)removeRecursivelyremoveRecursivelyremoveRecursivelyremoveRecursively(success, fail)(success, fail)(success, fail)(success, fail)

Delete a directory and all of its contents

Page 51: Local Storage

File Reader

It is used to read the contents of a file

Files can be read as text or as a base64 data encoded string

You can also abort() e file reading activity

You can register your own event listeners to receive the following events:

loadstart, progress, load, loadend, error, abort

Page 52: Local Storage

File Reader Example

entry.file(win, fail);

function win(file) {

var reader = new FileReader();

reader.onloadend = function(evt) {

console.log(evt.target.result);

};

reader.readAsText(file);

// reader.abort();// reader.abort();

};

function fail(evt) {

console.log(error.code);

};

Page 53: Local Storage

File Writer

It is used to write to a file

The data to be written must be UTFUTFUTFUTF----8 encoded8 encoded8 encoded8 encoded

You can register your own event listeners to receive You can register your own event listeners to receive the following events:

writestart, progress, write, writeend, error, abort

Page 54: Local Storage

File Writer

A FileWriter is created for a single filefor a single filefor a single filefor a single file

You can use it to write to a file multiple times�the FileWriter maintains the file's position and length

attributes, so you can seek and write anywhere in the file

By default, the FileWriter writes to the beginning of the file (will overwrite existing data)

Set the optional append boolean to true in the FileWriter's constructor to begin writing to the end of the file

Page 55: Local Storage

File Writer Methods

abort()abort()abort()abort()

Aborts writing fileAborts writing file

seek(byte)seek(byte)seek(byte)seek(byte)

Moves the file pointer to the byte specified.

truncate(length)truncate(length)truncate(length)truncate(length)

Shortens the file to the length specified.Shortens the file to the length specified.

write(data)write(data)write(data)write(data)

Writes data to the file

Page 56: Local Storage

File Writer Example

entry.createWriter(win, fail);

function win(writer) {

writer.onwrite = function(evt) {

console.log(“ok");

};

writer.write(“Ivano Malavolta");

};

function fail(evt) {function fail(evt) {

// error management

};

Page 57: Local Storage

Directory Reader

It is an object that lists files and directories lists files and directories lists files and directories lists files and directories in a directorydirectory

it has only one method:

readEntriesreadEntriesreadEntriesreadEntries(success, fail)(success, fail)(success, fail)(success, fail)

Read the entries of the directory

Page 58: Local Storage

Directory Reader Example

var directoryReader = dirEntry.createReader();

directoryReader.readEntries(success, fail);directoryReader.readEntries(success, fail);

function success(entries) {

var i;

for (i=0; i<entries.length; i++) {

console.log(entries[i].name);

}

}}

function fail(error) {

console.log(error.code);

}

Page 59: Local Storage

A Final Example: Looking for a file and reading it

window.requestFileSystem(window.PERSISTENT, 0, initFS, error);

function initFS(fs) {

fs.root.getFile(‘log.txt', {}, win, error);

}

function win(fileEntry) {

fileEntry.file(read, error);

}

function read(file) { function read(file) {

var reader = new FileReader();

reader.onloadend = function(e) {

console.log(this.result);

};

reader.readAsText(file);

}

function error(err) { console.log(err);}

Page 60: Local Storage

Roadmap

• Introduction

• Web Storage• Web Storage

• WebSQL

• IndexedDB

• File System Access

• Final Considerations• Final Considerations

Page 61: Local Storage

Final Considerations

You will likely use all of them in combination

�Use the right API for the right job

Web Web Web Web StorageStorageStorageStorage

• it is not transactional � race conditions

• very simple API, no schema • 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

• 5Mb quota

Page 62: Local Storage

Final Considerations

WebSQLWebSQLWebSQLWebSQL

• SQL-based � fast and efficient• SQL-based � fast and efficient

• transactional� more robust

• asynchronous � does not block the UI

• rigid data structure � data integrity vs agility

• 5Mb quota• 5Mb quota

Page 63: Local Storage

Final Considerations

IndexedDBIndexedDBIndexedDBIndexedDB

• simple data model � easy to use• 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• data is unstructured � integrity problems

• 5Mb quota

Page 64: Local Storage

Final Considerations

File SystemFile SystemFile SystemFile System

• asynchronous � does not block the UI• asynchronous � does not block the UI

• not transactional

• indexing and search are not built-in� you have to implement your lookup functions

• unlimited storage– useful for images, videos, documents, etc.

Page 65: Local Storage

References

http://docs.phonegap.com/en/1.7.0/


Recommended