Local Storage


Published on

Mobile applications Development - Lecture 13

Local/Session Storage
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).


Published in: Technology, Business
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Local Storage

  1. 1. Local Storage Ivano Malavolta ivano.malavolta@univaq.ithttp://www.di.univaq.it/malavolta
  2. 2. Roadmap• Introduction• Web Storage• WebSQL• IndexedDB• File System Access• Final Considerations
  3. 3. IntroductionThere are 4 ways to store data locally• Web storage – Local Storage – Session Storage• WebSQL• Indexed DB• File System Access
  4. 4. 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
  5. 5. 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
  6. 6. 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
  7. 7. IntroductionMobile browsers compatibility matrix
  8. 8. Roadmap• Introduction• Web Storage• WebSQL• IndexedDB• File System Access• Final Considerations
  9. 9. 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”);
  10. 10. 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
  11. 11. 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
  12. 12. 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”));
  13. 13. 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}
  14. 14. 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]);}
  15. 15. Counting ElementsAlso in this case, we have to do it manuallyvar usersNumber = JSON.parse(window.localStorage.getItem(“users“)).length;
  16. 16. Session StorageSession Storage provides the same interface as Local Storage you can call the same methodsbut Session Storage is cleared between app launches
  17. 17. Roadmap• Introduction• Web Storage• WebSQL• IndexedDB• File System Access• Final Considerations
  18. 18. 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 });
  19. 19. 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
  20. 20. 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
  21. 21. 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
  22. 22. 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
  23. 23. Transaction Examplehttp://bit.ly/JlUJde
  24. 24. 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);}
  25. 25. 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
  26. 26. 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}
  27. 27. 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
  28. 28. 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); }}
  29. 29. 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
  30. 30. Error Code Example... tx.executeSql(‘SELECT * FROM USER‘,[], success, error);}function error(err) { console.log(err.code);}
  31. 31. Roadmap• Introduction• Web Storage• WebSQL• IndexedDB• File System Access• Final Considerations
  32. 32. 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
  33. 33. 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
  34. 34. Roadmap• Introduction• Web Storage• WebSQL• IndexedDB• File System Access• Final Considerations
  35. 35. 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
  36. 36. 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
  37. 37. 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
  38. 38. 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
  39. 39. Local File System Examplewindow.requestFileSystem( LocalFileSystem.PERSISTENT, 0, onSuccess, onError);function onSuccess(fileSystem) { console.log(fileSystem.name);}
  40. 40. 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
  41. 41. 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);}
  42. 42. EntitiesFileEntry The real objectsDirectoryEntryFile DescriptorFileReaderFileWriter Writing & Reading objectsDirectoryReader
  43. 43. 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
  44. 44. 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
  45. 45. 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
  46. 46. 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
  47. 47. Directory EntryIt represents a directory on a file systemIt has the same properties of FileEntry
  48. 48. 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
  49. 49. 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)
  50. 50. 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
  51. 51. 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
  52. 52. 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);};
  53. 53. 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
  54. 54. 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
  55. 55. 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
  56. 56. 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};
  57. 57. 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
  58. 58. 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);}
  59. 59. 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);}
  60. 60. Roadmap• Introduction• Web Storage• WebSQL• IndexedDB• File System Access• Final Considerations
  61. 61. 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
  62. 62. 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
  63. 63. 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
  64. 64. 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.
  65. 65. Referenceshttp://docs.phonegap.com/en/1.7.0/