Local Storage
Upcoming SlideShare
Loading in...5
×
 

Local Storage

on

  • 1,271 views

Mobile applications Development - Lecture 13 ...

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

Statistics

Views

Total Views
1,271
Views on SlideShare
1,270
Embed Views
1

Actions

Likes
1
Downloads
76
Comments
0

1 Embed 1

http://www.docseek.net 1

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Local Storage Local Storage Presentation Transcript

  • Local Storage Ivano Malavolta ivano.malavolta@univaq.ithttp://www.di.univaq.it/malavolta
  • Roadmap• Introduction• Web Storage• WebSQL• IndexedDB• File System Access• Final Considerations
  • IntroductionThere are 4 ways to store data locally• Web storage – Local Storage – Session Storage• WebSQL• Indexed DB• File System Access
  • Web StorageLocalStorage stores data in key/value pairs persists across browser sessionsSessionStorage stores data in key/value pairs data is erased when a browser session ends
  • IntroductionWebSQL Database relational DB support for tables creation, insert, update, … transactional persists across browser sessionsIts evolution is called IndexedDB but it is actually IndexedDB, not supported by most mobile browsers
  • IntroductionFile System Access you 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
  • IntroductionMobile browsers compatibility matrix
  • Roadmap• Introduction• Web Storage• WebSQL• IndexedDB• File System Access• Final Considerations
  • Web StorageIt is based on a single persistent object called localStorageYou can set values by calling window.localStorage.setItem(“name”, “Ivano”);You can get values back by callingvar name = window.localStorage.getItem(“name”);
  • Supported MethodslocalStorage.key(0) Returns the name of the key at the position specifiedgetItem(“key”) Returns the item identified by its keysetItem(“key”, “value”) Saves and item at the key providedremoveItem(“hey”) Removes the item identified by its keyclear() Removes all of the key value pairs
  • Complex ObjectsCurrent implementations support only string-to-string mappings you can store only strings keys can be only stringsYou 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 ExistenceYou can simply check if the needed element is == nullif (window.localStorage.getItem(“user”)) { // there is an object in user} else { // the user key does not have any value}
  • Selecting elementsIn this case you have to manually iterate on elementsvar 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]);}
  • Counting ElementsAlso in this case, we have to do it manuallyvar usersNumber = JSON.parse(window.localStorage.getItem(“users“)).length;
  • Session StorageSession Storage provides the same interface as Local Storage you can call the same methodsbut Session Storage is cleared between app launches
  • Roadmap• Introduction• Web Storage• WebSQL• IndexedDB• File System Access• Final Considerations
  • WebSQLIt provides you a structured SQL relational databaseYou have to setup a DB schemaYou can then perform classical SQL queries tx.executeSql("SELECT * FROM User“, [], function(tx, result) { // callback code });
  • Opening a DBDone via a dedicated functionvar db = openDatabase(‘Test, ‘1.0, ‘Test DB, 100000);It creates a new SQLLite DB and returns a new Database objectThe Database object will be used to manipulate the data
  • Opening a DB: syntax openDatabase(name, version, displayname, size);DB name the name of the DBDB version the version of the DBDB Display name the display name of the DBDB Size the size of the DB in bytes
  • DatabaseIt 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
  • TransactionsIt allow you to execute SQL statements against the DB db.transaction(queries, error, success);3 callback functions:queries : contains the queries to be performederror : executed if the transaction results in an errorsuccess : executed if the transaction terminates correctly
  • Transaction Examplehttp://bit.ly/JlUJde
  • executeSqlIt is the method that performs a SQL statementThe user can build up a database transaction by calling the executeSql method multiple timesfunction 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 SetsWhen the executeSql method is called, it will invoke its callback with a SQLResultSet parameterIt has 3 properties:insertId the ID of the row that has been insertedrowsAffected the number of rows changed by the SQL statementrows 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 (1, ?, ?)‘, [“Ivano“, “Malavolta“], success, error);}function success(tx, results) { var affected = results.rowsAffected(); // 1}function error(err) { // code for managing the error}
  • Result Set ListsIt contains the data returned from a SQL Select statementlength the number of rows returned by the SQL queryitem(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); }}
  • ErrorsIt contains information about an occurred errorcode A predefined error code es. UNKNOWN_ERR, DATABASE_ERR, TOO_LARGE_ERR, QUOTA_ERR, SYNTAX_ERR, TIMEOUT_ERRmessage A description of the error
  • Error Code Example... tx.executeSql(‘SELECT * FROM USER‘,[], success, error);}function error(err) { console.log(err.code);}
  • Roadmap• Introduction• Web Storage• WebSQL• IndexedDB• File System Access• Final Considerations
  • Indexed DBIt tries to combine Web Storage and WebSQLYou can save data as key/value pairs key/valueYou can define multiple DBsGood Performance data is indexed asynchronous it does not block the UI
  • Indexed DBAn Indexed DB is a collection of object storesYou can drop objects into the storesYou can see stores as a big SQL table with only key/value key/value pairs you don’t need to define a schema upfront
  • Roadmap• Introduction• Web Storage• WebSQL• IndexedDB• File System Access• Final Considerations
  • File System AccessIt allows you to read, write and navigate file system hierarchiesIt is fundamental for managing and storing large files client- and binary content on the client-side
  • File System Access Workflow1. Request file system access – persistent or temporary file system2. then you can perform CRUD operations for both files and folders: – Create – Read – Update – Delete
  • Request File SystemrequestFileSystem(type, size, successCb, [errorCb])type LocalFileSystem.TEMPORARY LocalFileSystem .PERSISTENTsize size in bytes the app will require for storage.successCb success callback, its argument is a FileSystem objectErrorCb error callback, its argument is a FileError object
  • Temporary VS PersistentTemporary the files stored by the app can be deleted at the browser’s discretion no guarantee of persistencePersistent cannot be deleted by the browser without authorization by the app
  • Local File System Examplewindow.requestFileSystem( LocalFileSystem.PERSISTENT, 0, onSuccess, onError);function onSuccess(fileSystem) { console.log(fileSystem.name);}
  • File SystemThe FileSystem object has 2 properties:name the name of the file system it is unique across the list of exposed file systemsroot the DirectoryEntry object representing the root folder of the file system
  • Resolving a File URIresolveLocalFileSystemURI retrieve a DirectoryEntry or FileEntry using a URIwindow.resolveLocalFileSystemURI( "file:///userImg.png", onSuccess, onError);function onSuccess(fileEntry) { console.log(fileEntry.name);}
  • EntitiesFileEntry The real objectsDirectoryEntryFile DescriptorFileReaderFileWriter Writing & Reading objectsDirectoryReader
  • File EntryIt represents a file on a file systemisFile (boolean) Always trueisDirectory (boolean) Always falsename (DOMString) the name of the FileEntry, excluding the pathfullPath (DOMString) the full absolute path from the root
  • File Entry MethodsgetMetadata(success,getMetadata(success, fail) Look up metadata about a filemoveTo(parentEntry, newName, success, fail)moveTo( parentEntry, newName, Move a file to a different location on the file systemcopyTo(parentEntry, newName, success, fail)copyTo(parentEntry, newName, Copy a file to a different location on the file systemtoURI()toURI() Return a URI that can be used to locate a file
  • File Entry Methodsremove(success, fail) Delete a filegetParent(success,getParent(success, fail) Look up the parent directorycreateWriter(success,createWriter(success, fail) Creates a FileWriter object that can be used to write to a filefile(success, fail) Creates a File object containing file properties
  • FileIt contains attributes of a single filename (DOMString) The name of the filefullPath (DOMString) The full path of the file including the file nametype (DOMString) The mime type of the filelastModifiedDate (Date) The last time the file was modifiedsize (long)The size of the file in bytes
  • Directory EntryIt represents a directory on a file systemIt has the same properties of FileEntry
  • Directory Entry MethodsgetMetadata(success,getMetadata(success, fail) Look up metadata about a directorymoveTo(parentEntry, newName,moveTo(parentEntry , newName, success, fail) Move a directory to a different location on the file systemcopyTo(parentEntry, newName,copyTo(parentEntry, newName, success, fail) Copy a directory to a different location on the file systemtoURI()toURI() Return a URI that can be used to locate a directory
  • Directory Entry MethodsgetParent(success, fail)getParent(success, Look up the parent directorycreateReader()createReader() Creates a DirectoryReader object that can be used to read a directorygetDirectory(path, options, success, fail)getDirectory(path, Create or look up a directory options: create (true | false) exclusive (true | false)
  • Directory Entry MethodsgetFile(path, options, success, fail)getFile(path, Create or look up a file within the directory options: create (true | false) exclusive (true | false)removeRecursively(success, fail)removeRecursively(success, Delete a directory and all of its contents
  • File ReaderIt is used to read the contents of a fileFiles can be read as text or as a base64 data encoded stringYou can also abort() e file reading activityYou can register your own event listeners to receive the following events: loadstart, progress, load, loadend, error, abort
  • File Reader Exampleentry.file(win, fail);function win(file) { var reader = new FileReader(); reader.onloadend = function(evt) { console.log(evt.target.result); }; reader.readAsText(file); // reader.abort();};function fail(evt) { console.log(error.code);};
  • File WriterIt is used to write to a fileThe data to be written must be UTF-8 encoded UTF-You can register your own event listeners to receive the following events: writestart, progress, write, writeend, error, abort
  • File WriterA FileWriter is created for a single fileYou can use it to write to a file multiple times the FileWriter maintains the files position and length attributes, so you can seek and write anywhere in the fileBy default, the FileWriter writes to the beginning of the file (will overwrite existing data)Set the optional append boolean to true in the FileWriters constructor to begin writing to the end of the file
  • File Writer Methodsabort() Aborts writing fileseek(byte) Moves the file pointer to the byte specified.truncate(length) Shortens the file to the length specified.write(data) Writes data to the file
  • File Writer Exampleentry.createWriter(win, fail);function win(writer) { writer.onwrite = function(evt) { console.log(“ok"); }; writer.write(“Ivano Malavolta");};function fail(evt) { // error management};
  • Directory ReaderIt is an object that lists files and directories in a directoryit has only one method:readEntries(success,readEntries(success, fail) Read the entries of the directory
  • Directory Reader Examplevar directoryReader = dirEntry.createReader();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);}
  • A Final Example: Looking for a file and reading itwindow.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) { var reader = new FileReader(); reader.onloadend = function(e) { console.log(this.result); }; reader.readAsText(file);}function error(err) { console.log(err);}
  • Roadmap• Introduction• Web Storage• WebSQL• IndexedDB• File System Access• Final Considerations
  • Final ConsiderationsYou will likely use all of them in combination Use the right API for the right jobWeb 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• 5Mb quota
  • Final ConsiderationsWebSQL• SQL-based fast and efficient• transactional more robust• asynchronous does not block the UI• rigid data structure data integrity vs agility• 5Mb quota
  • Final ConsiderationsIndexedDB• 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• 5Mb quota
  • Final ConsiderationsFile System• 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.
  • Referenceshttp://docs.phonegap.com/en/1.7.0/