SlideShare a Scribd company logo
1 of 70
STORAGE
By: Michael T. Shrove
CPE 490/590 Smartphone Programming
University of Alabama Huntsville
ANDROID
Storage Options
• Android provides several
options for you to save
persistent application
data.
• The solution you choose
depends on your specific
needs, such as whether
the data should be
private to your
application or accessible
to other applications
(and the user) and how
much space your data
requires.
Storage Options
• Your data storage options are the following:
• Shared Preferences
• Store private primitive data in key-value pairs.
• Internal Storage
• Store private data on the device memory.
• External Storage
• Store public data on the shared external storage.
• SQLite Databases
• Store structured data in a private database.
• Network Connection
• Store data on the web with your own network server.
Using Shared Preferences
• The SharedPreferences class provides a general
framework that allows you to save and retrieve persistent
key-value pairs of primitive data types.
• You can use SharedPreferences to save any primitive
data: booleans, floats, ints, longs, and strings.
• This data will persist across user sessions (even if your
application is killed).
• Android provides the SharedPreferences object to help
you save simple application data.
• You may need to save to a file if your preferences are
more complicated than normal.
Getting Shared Preferences
• To get a SharedPreferences object for your
application, use one of two methods:
• getSharedPreferences()
• Use this if you need multiple preferences files identified by name,
which you specify with the first parameter.
• getPreferences()
• Use this if you need only one preferences file for your Activity.
• Because this will be the only preferences file for your Activity, you
don't supply a name.
Read and Write to Preferences
• To write values:
• Call edit() to get a SharedPreferences.Editor.
• Add values with methods such as putBoolean() and
putString().
• Commit the new values with commit()
• To read values:
• Use SharedPreferences methods such as
getBoolean() and getString().
Example
Read
Write
Easier Way to Get Preferences
Using Internal Storage
• You can save files directly on the device's internal
storage.
• By default, files saved to the internal storage are private
to your application and other applications cannot access
them (nor can the user).
• When the user uninstalls your application, these files are
removed.
Internal Storage Steps
• To create and write a private file to the internal
storage:
• Call openFileOutput() with the name of the file and the
operating mode. This returns a FileOutputStream.
• Write to the file with write().
• Close the stream with close().
Example
• MODE_PRIVATE will create the file (or replace a file of the same name) and
make it private to your application.
• Other modes available are: MODE_APPEND, MODE_WORLD_READABLE,
and MODE_WORLD_WRITEABLE.
Example Writing using OutputStreamWriter
Read from Internal Storage
• To read a file from internal storage:
• Call openFileInput() and pass it the name of the file to
read. This returns a FileInputStream.
• Read bytes from the file with read()
• Then close the stream with close()
Example using InputStreamReader
Saving Cache Files
• If you'd like to cache some data, rather than store it
persistently, you should use getCacheDir()
• This will open a File that represents the internal directory
where your application should save temporary cache files.
• When the device is low on internal storage space, Android
may delete these cache files to recover space.
• However, you should not rely on the system to clean up
these files for you.
• You should always maintain the cache files yourself and
stay within a reasonable limit of space consumed, such as
1MB.
• When the user uninstalls your application, these files are
removed.
Other Useful Methods
• getFilesDir()
• Gets the absolute path to the filesystem directory where your
internal files are saved.
• getDir()
• Creates (or opens an existing) directory within your internal storage
space.
• deleteFile()
• Deletes a file saved on the internal storage.
• fileList()
• Returns an array of files currently saved by your application.
External Storage
• Every Android-compatible device supports a shared
"external storage" that you can use to save files.
• This can be a removable storage media (such as an SD
card) or an internal (non-removable) storage.
• Files saved to the external storage are world-readable
and can be modified by the user when they enable USB
mass storage to transfer files on a computer.
Saving files that can be shared with other apps
• Generally, new files that the user may acquire through
your app should be saved to a "public" location on the
device where other apps can access them and the user
can easily copy them from the device.
• When doing so, you should use to one of the shared
public directories, such as Music/, Pictures/, and
Ringtones/.
Caution on External Storage
• External storage can become unavailable if the user
mounts the external storage on a computer or removes
the media, and there's no security enforced upon files you
save to the external storage.
• All applications can read and write files placed on the
external storage and the user can remove them.
Getting Access to External Storage
• In order to read or write files on the external storage, your
app must acquire the READ_EXTERNAL_STORAGE or
WRITE_EXTERNAL_STORAGE system permissions.
• For example:
• Note: If you need to both read and write files, then you
need to request only the WRITE_EXTERNAL_STORAGE
permission, because it implicitly requires read access as
well.
Example
Example
Using Databases
• Android provides full support for SQLite databases.
• Any databases you create will be accessible by name to
any class in the application, but not outside the
application.
• The recommended method to create a new SQLite
database is to create a subclass of SQLiteOpenHelper
and override the onCreate() method, in which you can
execute a SQLite command to create tables in the
database.
SQLite
• Like iOS, Android also uses SQLite for databases.
• Use SQL statements in order to create databases in the
file system.
• Can create databases on SD card or internal space.
• If database is create on internal memory, it can be located
at:
• /data/data/<package_name>/databases/ folder
DBAdapter Helper Class
• A good practice when dealing with database in Android is
to built a helper class.
• Usually inside the helper class is a class called
DBAdapter which also helps with the database code.
• Keeps the complex algorithms dealing with databases in
one class.
• Custom class.
Database Helper Class
• Android created class.
• Extends the SQLOpenHelper
• Used to create the database if not there.
• Used to upgrade the databases if something has
changed.
DBAdapter Beginnings
Open and Close Database
Insert Rows
Delete Rows
Get Rows of Data
Update Rows
Using the DBAdapter Class
Using Cursor Object
IOS
NSUserDefault
• The NSUserDefaults class provides a programmatic
interface for interacting with the defaults system.
• The defaults system allows an application to customize its
behavior to match a user’s preferences.
• For example, you can allow users to determine what units
of measurement your application displays or how often
documents are automatically saved.
• Applications record such preferences by assigning values
to a set of parameters in a user’s defaults database.
• The parameters are referred to as defaults since they’re
commonly used to determine an application’s default state
at startup or the way it acts by default.
NSUserDefaults
• At runtime, you use an NSUserDefaults object to read the
defaults that your application uses from a user’s defaults
database.
• NSUserDefaults caches the information to avoid having
to open the user’s defaults database each time you need
a default value.
• The synchronize method, which is automatically invoked
at periodic intervals, keeps the in-memory cache in sync
with a user’s defaults database.
NSUserDefaults Supported Variable
Types
• NSData
• String
• NSNumber
• UInt
• Int
• Float
• Double
• Bool
• NSDate
• Array
• Dictionary
Example of Writing to NSUserDefaults
Sample Methods in NSUserDefaults
• There are several convenience methods for storing
data in NSUserDefaults they include:
• func setBool(value: Bool, forKey defaultName: String)
• func setInteger(value: Int, forKey defaultName: String)
• func setFloat(value: Float, forKey defaultName: String)
• func setDouble(value: Double, forKey defaultName: String)
• func setObject(value: AnyObject?, forKey defaultName: String)
• func setURL(url: NSURL, forKey defaultName: String)
Reading from NSUserDefaults
• Reading is done in a very similar fashion.
• You need to get a reference to the NSUserDefaults object,
and then ask it for the value you want.
• In the case of reading out the String we wrote in and
printing it to the console, we would use the code:
Sample Methods in NSUserDefaults
• Much like writing to NSUserDefaults, there are several
convenience methods for reading data back out, that are a
bit more full featured than writing them:
• func boolForKey(defaultName: String) -> Bool
• func integerForKey(defaultName: String) -> Int
• func floatForKey(defaultName: String) -> Float
• func doubleForKey(defaultName: String) -> Double
• func objectForKey(defaultName: String) -> AnyObject?
• func URLForKey(defaultName: String) -> NSURL?
• func dataForKey(defaultName: String) -> NSData?
• func stringForKey(defaultName: String) -> String?
• func stringArrayForKey(defaultName: String) -> [AnyObject]?
• func arrayForKey(defaultName: String) -> [AnyObject]?
• func dictionaryForKey(defaultName: String) -> [NSObject :
AnyObject]?
File I/O
Usage of Files
• When downloading data, instead of keeping all the data in
memory, a more effective and memory-efficient method is
to save them in a file.
• Memory is minimum in mobile phones.
• Saving to a file is also useful for data that you want to
retrieve even after the app as shut down and restarted.
Sandbox
• An iOS app’s interactions with the file system are limited
mostly to the directories inside the app’s sandbox.
• During installation of a new app, the installer creates a
number of containers for the app.
• Each container has a specific role. The bundle container
holds the app’s bundle, whereas the data container holds
data for both the application and the user.
• The data container is further divided into a number of
directories that the app can use to sort and organize its
data.
Sandbox
• Because it is in a
sandbox, an app is
generally prohibited from
accessing or creating
files outside its
containers.
• One exception to this
rule occurs when an app
uses public system
interfaces to access
things such as the user’s
contacts or music.
iOS Standard Directories
• For security purposes, an iOS app has limited a number
of places where it can write its data.
• When an app is installed on a device (either from iTunes
or the App Store), the system creates a number of
containers for the app.
• These containers represent the universe for that app and
contain everything the app can access directly.
iOS Standard Directories
Directory Description
AppName.app This is the app’s bundle. This directory contains the app and
all of its resources.
Documents/ Use this directory to store user-generated content. The
contents of this directory can be made available to the user
through file sharing; therefore, his directory should only
contain files that you may wish to expose to the user.
The contents of this directory are backed up by iTunes.
Documents/Inbox Use this directory to access files that your app was asked to
open by outside entities. Specifically, the Mail program
places email attachments associated with your app in this
directory. Document interaction controllers may also place
files in it.
Your app can read and delete files in this directory but cannot
create new files or write to existing files.
iOS Standard Directories
Directory Description
Library/ This is the top-level directory for any files that are not user data
files. You typically put files in one of several standard
subdirectories. iOS apps commonly use the Application Support
and Caches subdirectories; however, you can create custom
subdirectories.
Use the Library subdirectories for any files you don’t want
exposed to the user. Your app should not use these directories for
user data files.
The contents of the Library directory (with the exception of the
Caches subdirectory) are backed up by iTunes.
tmp/ Use this directory to write temporary files that do not need to
persist between launches of your app. Your app should remove
files from this directory when they are no longer needed; however,
the system may purge this directory when your app is not running.
The contents of this directory are not backed up by iTunes.
FilePaths
• Get the contents of file directory in the /Resources
directory
• Just replace /Resources with other directory path.
Creating an NSFileManger instance
• Before proceeding, first we need to recap the steps
necessary to obtain a reference to the application’s
NSFileManager instance.
• As discussed in the previous chapter, the NSFileManager
class contains a class method named defaultManager
that is used to obtain a reference.
Check for the Existence of a File
• The NSFileManager class contains an instance method
named fileExistsAtPath which checks whether a specified
file already exists.
• The method takes as an argument an NSString object
containing the path to the file in question and returns a
Boolean value indicating the presence or otherwise of the
specified file:
Moving/Rename a File
Copying a File
Removing a File
NSFileHandle
• An NSFileHandle object can be created when opening a
file for reading, writing or updating (in other words both
reading and writing).
• Having opened a file, it must subsequently be closed
when we have finished working with it using the closeFile
method.
• If an attempt to open a file fails, for example because an
attempt is made to open a non-existent file for reading,
these methods return nil.
Example of NSFileHandle
NSFileHandle Offset
• NSFileHandle objects maintain a pointer to the current
position in a file.
• This is referred to as the offset. When a file is first opened
the offset is set to 0 (the beginning of the file).
• This means that any read or write operations performed
using the NSFileHandle instance methods will take place
at offset 0 in the file.
• To perform operations at different locations in a file (for
example to append data to the end of the file) it is first
necessary to seek to the required offset.
NSFileHandle Offset
Reading from File
• Once a file has been opened and assigned a file handle,
the contents of that file may be read from the current
offset position.
• The readDataOfLength method reads a specified
number of bytes of data from the file starting at the current
offset.
• For example, the following code on the next slide reads 5
bytes of data from offset 10 in a file.
• The data read is returned encapsulated in an NSData
object:
Example of Reading a File
Alternatively, the readDataToEndOfFile method will read all the data in the file
starting at the current offset and ending at the end of the file.
Writing to File
• The writeData method writes the data contained in an
NSData object to the file starting at the location of the
offset.
• Note that this does not insert data but rather overwrites
any existing data in the file at the corresponding location.
Example of Writing Data to File
Database
FMDB
• FMDB is an Objective-C wrapper around SQLite
• Because swift is not Objective-C and SQLite was written
using the C language, we have to use a wrapper.
• Open Source Library
• https://github.com/ccgus/fmdb
Open and Create
Insert into Database
Query from Database
References
• http://www.theappguruz.com/tutorial/use-sqlite-database-
swift/
• http://www.theappguruz.com/tutorial/use-sqlite-database-
swift/
• https://github.com/ccgus/fmdb
• http://www.techotopia.com/index.php/Swift_iOS_8_Datab
ase_Implementation_using_SQLite
• http://developer.android.com
• http://developer.apple.com

More Related Content

What's hot

Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and OutputEduardo Bergavera
 
What is in a Lucene index?
What is in a Lucene index?What is in a Lucene index?
What is in a Lucene index?lucenerevolution
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsAnton Keks
 
Munching & crunching - Lucene index post-processing
Munching & crunching - Lucene index post-processingMunching & crunching - Lucene index post-processing
Munching & crunching - Lucene index post-processingabial
 
I/O in java Part 1
I/O in java Part 1I/O in java Part 1
I/O in java Part 1ashishspace
 
SQLite Database Tutorial In Android
SQLite Database Tutorial In AndroidSQLite Database Tutorial In Android
SQLite Database Tutorial In AndroidAndroid 5
 
Chapter 3 part 1
Chapter 3 part 1Chapter 3 part 1
Chapter 3 part 1rohassanie
 
Berlin Buzzwords 2013 - How does lucene store your data?
Berlin Buzzwords 2013 - How does lucene store your data?Berlin Buzzwords 2013 - How does lucene store your data?
Berlin Buzzwords 2013 - How does lucene store your data?Adrien Grand
 
Session 22 - Java IO, Serialization
Session 22 - Java IO, SerializationSession 22 - Java IO, Serialization
Session 22 - Java IO, SerializationPawanMM
 
Chapter 3 part 2
Chapter 3 part 2Chapter 3 part 2
Chapter 3 part 2rohassanie
 
Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output ConceptsVicter Paul
 
L21 io streams
L21 io streamsL21 io streams
L21 io streamsteach4uin
 
Session 23 - JDBC
Session 23 - JDBCSession 23 - JDBC
Session 23 - JDBCPawanMM
 

What's hot (20)

Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and Output
 
What is in a Lucene index?
What is in a Lucene index?What is in a Lucene index?
What is in a Lucene index?
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
 
Munching & crunching - Lucene index post-processing
Munching & crunching - Lucene index post-processingMunching & crunching - Lucene index post-processing
Munching & crunching - Lucene index post-processing
 
Handling I/O in Java
Handling I/O in JavaHandling I/O in Java
Handling I/O in Java
 
Lucene indexing
Lucene indexingLucene indexing
Lucene indexing
 
I/O in java Part 1
I/O in java Part 1I/O in java Part 1
I/O in java Part 1
 
SQLite Database Tutorial In Android
SQLite Database Tutorial In AndroidSQLite Database Tutorial In Android
SQLite Database Tutorial In Android
 
Java I/O
Java I/OJava I/O
Java I/O
 
File Systems
File SystemsFile Systems
File Systems
 
Input output streams
Input output streamsInput output streams
Input output streams
 
Chapter 3 part 1
Chapter 3 part 1Chapter 3 part 1
Chapter 3 part 1
 
Berlin Buzzwords 2013 - How does lucene store your data?
Berlin Buzzwords 2013 - How does lucene store your data?Berlin Buzzwords 2013 - How does lucene store your data?
Berlin Buzzwords 2013 - How does lucene store your data?
 
Session 22 - Java IO, Serialization
Session 22 - Java IO, SerializationSession 22 - Java IO, Serialization
Session 22 - Java IO, Serialization
 
Chapter 3 part 2
Chapter 3 part 2Chapter 3 part 2
Chapter 3 part 2
 
Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output Concepts
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
 
32.java input-output
32.java input-output32.java input-output
32.java input-output
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Session 23 - JDBC
Session 23 - JDBCSession 23 - JDBC
Session 23 - JDBC
 

Viewers also liked

Taking Swift for a spin
Taking Swift for a spinTaking Swift for a spin
Taking Swift for a spinThoughtworks
 
Android and IOS UI Development (Android 5.0 and iOS 9.0)
Android and IOS UI Development (Android 5.0 and iOS 9.0)Android and IOS UI Development (Android 5.0 and iOS 9.0)
Android and IOS UI Development (Android 5.0 and iOS 9.0)Michael Shrove
 
Building Digital Success: I need a BA
Building Digital Success: I need a BABuilding Digital Success: I need a BA
Building Digital Success: I need a BAIIBA UK Chapter
 
Swift Office Hours - Launch Event
Swift Office Hours - Launch EventSwift Office Hours - Launch Event
Swift Office Hours - Launch EventNareg Khoshafian
 
Ch14-Software Engineering 9
Ch14-Software Engineering 9Ch14-Software Engineering 9
Ch14-Software Engineering 9Ian Sommerville
 
Accelerating Agile by Adding Business Analysis
Accelerating Agile by Adding Business AnalysisAccelerating Agile by Adding Business Analysis
Accelerating Agile by Adding Business AnalysisIIBA UK Chapter
 
Starlight taylor swift for women 2014 عطر ستريت تيلور سويفت نسائي
Starlight taylor swift for women  2014  عطر  ستريت  تيلور سويفت نسائيStarlight taylor swift for women  2014  عطر  ستريت  تيلور سويفت نسائي
Starlight taylor swift for women 2014 عطر ستريت تيلور سويفت نسائيAZ Panor
 
Agile Product Development: Scaled Delivery
Agile Product Development: Scaled DeliveryAgile Product Development: Scaled Delivery
Agile Product Development: Scaled DeliveryIIBA UK Chapter
 
Swift Buildpack for Cloud Foundry
Swift Buildpack for Cloud FoundrySwift Buildpack for Cloud Foundry
Swift Buildpack for Cloud FoundryRobert Gogolok
 
Background Audio Playback
Background Audio PlaybackBackground Audio Playback
Background Audio PlaybackKorhan Bircan
 
The Power of an Agile BA
The Power of an Agile BAThe Power of an Agile BA
The Power of an Agile BAIIBA UK Chapter
 
ios_summit_2016_korhan
ios_summit_2016_korhanios_summit_2016_korhan
ios_summit_2016_korhanKorhan Bircan
 
Detecting Problematic Lookup Functions in Spreadsheets
Detecting Problematic Lookup Functions in Spreadsheets Detecting Problematic Lookup Functions in Spreadsheets
Detecting Problematic Lookup Functions in Spreadsheets icseconf
 

Viewers also liked (20)

Taking Swift for a spin
Taking Swift for a spinTaking Swift for a spin
Taking Swift for a spin
 
Sensors 9
Sensors   9Sensors   9
Sensors 9
 
Android and IOS UI Development (Android 5.0 and iOS 9.0)
Android and IOS UI Development (Android 5.0 and iOS 9.0)Android and IOS UI Development (Android 5.0 and iOS 9.0)
Android and IOS UI Development (Android 5.0 and iOS 9.0)
 
Basics 4
Basics   4Basics   4
Basics 4
 
Building Digital Success: I need a BA
Building Digital Success: I need a BABuilding Digital Success: I need a BA
Building Digital Success: I need a BA
 
Swift Office Hours - Launch Event
Swift Office Hours - Launch EventSwift Office Hours - Launch Event
Swift Office Hours - Launch Event
 
Korhan bircan
Korhan bircanKorhan bircan
Korhan bircan
 
Ch14-Software Engineering 9
Ch14-Software Engineering 9Ch14-Software Engineering 9
Ch14-Software Engineering 9
 
3 swift 컬렉션
3 swift 컬렉션3 swift 컬렉션
3 swift 컬렉션
 
Accelerating Agile by Adding Business Analysis
Accelerating Agile by Adding Business AnalysisAccelerating Agile by Adding Business Analysis
Accelerating Agile by Adding Business Analysis
 
Starlight taylor swift for women 2014 عطر ستريت تيلور سويفت نسائي
Starlight taylor swift for women  2014  عطر  ستريت  تيلور سويفت نسائيStarlight taylor swift for women  2014  عطر  ستريت  تيلور سويفت نسائي
Starlight taylor swift for women 2014 عطر ستريت تيلور سويفت نسائي
 
Java 2
Java   2Java   2
Java 2
 
Agile Product Development: Scaled Delivery
Agile Product Development: Scaled DeliveryAgile Product Development: Scaled Delivery
Agile Product Development: Scaled Delivery
 
Swift Buildpack for Cloud Foundry
Swift Buildpack for Cloud FoundrySwift Buildpack for Cloud Foundry
Swift Buildpack for Cloud Foundry
 
Just get out of the way
Just get out of the wayJust get out of the way
Just get out of the way
 
Going Swiftly Functional
Going Swiftly FunctionalGoing Swiftly Functional
Going Swiftly Functional
 
Background Audio Playback
Background Audio PlaybackBackground Audio Playback
Background Audio Playback
 
The Power of an Agile BA
The Power of an Agile BAThe Power of an Agile BA
The Power of an Agile BA
 
ios_summit_2016_korhan
ios_summit_2016_korhanios_summit_2016_korhan
ios_summit_2016_korhan
 
Detecting Problematic Lookup Functions in Spreadsheets
Detecting Problematic Lookup Functions in Spreadsheets Detecting Problematic Lookup Functions in Spreadsheets
Detecting Problematic Lookup Functions in Spreadsheets
 

Similar to Storage 8

Android datastorage
Android datastorageAndroid datastorage
Android datastorageKrazy Koder
 
Android local databases
Android local databasesAndroid local databases
Android local databasesFatimaYousif11
 
iOS Application Penetration Testing for Beginners
iOS Application Penetration Testing for BeginnersiOS Application Penetration Testing for Beginners
iOS Application Penetration Testing for BeginnersRyanISI
 
iOS Beginners Lesson 3
iOS Beginners Lesson 3iOS Beginners Lesson 3
iOS Beginners Lesson 3Calvin Cheng
 
Corporate-informatica-training-in-mumbai
Corporate-informatica-training-in-mumbaiCorporate-informatica-training-in-mumbai
Corporate-informatica-training-in-mumbaiUnmesh Baile
 
Corporate-informatica-training-in-mumbai
Corporate-informatica-training-in-mumbaiCorporate-informatica-training-in-mumbai
Corporate-informatica-training-in-mumbaiUnmesh Baile
 
CNIT 121: 13 Investigating Mac OS X Systems
CNIT 121: 13 Investigating Mac OS X SystemsCNIT 121: 13 Investigating Mac OS X Systems
CNIT 121: 13 Investigating Mac OS X SystemsSam Bowne
 
Codeigniter Training Part3
Codeigniter Training Part3Codeigniter Training Part3
Codeigniter Training Part3Weerayut Hongsa
 
CS3270 - DATABASE SYSTEM - Lecture (1)
CS3270 - DATABASE SYSTEM -  Lecture (1)CS3270 - DATABASE SYSTEM -  Lecture (1)
CS3270 - DATABASE SYSTEM - Lecture (1)Dilawar Khan
 
ASP.NET Session 7
ASP.NET Session 7ASP.NET Session 7
ASP.NET Session 7Sisir Ghosh
 
Information Retrieval - Data Science Bootcamp
Information Retrieval - Data Science BootcampInformation Retrieval - Data Science Bootcamp
Information Retrieval - Data Science BootcampKais Hassan, PhD
 
Linux System Programming - File I/O
Linux System Programming - File I/O Linux System Programming - File I/O
Linux System Programming - File I/O YourHelper1
 
Solr Recipes Workshop
Solr Recipes WorkshopSolr Recipes Workshop
Solr Recipes WorkshopErik Hatcher
 
CNIT 152: 13 Investigating Mac OS X Systems
CNIT 152: 13 Investigating Mac OS X SystemsCNIT 152: 13 Investigating Mac OS X Systems
CNIT 152: 13 Investigating Mac OS X SystemsSam Bowne
 
Android Training Ahmedabad , Android Course Ahmedabad, Android architecture
Android Training Ahmedabad , Android Course Ahmedabad, Android architectureAndroid Training Ahmedabad , Android Course Ahmedabad, Android architecture
Android Training Ahmedabad , Android Course Ahmedabad, Android architectureNicheTech Com. Solutions Pvt. Ltd.
 
Microsoft Offical Course 20410C_10
Microsoft Offical Course 20410C_10Microsoft Offical Course 20410C_10
Microsoft Offical Course 20410C_10gameaxt
 

Similar to Storage 8 (20)

Android datastorage
Android datastorageAndroid datastorage
Android datastorage
 
Memory management
Memory managementMemory management
Memory management
 
Android-data storage in android-chapter21
Android-data storage in android-chapter21Android-data storage in android-chapter21
Android-data storage in android-chapter21
 
Lab4 - android
Lab4 - androidLab4 - android
Lab4 - android
 
iOS Application Pentesting
iOS Application PentestingiOS Application Pentesting
iOS Application Pentesting
 
Android local databases
Android local databasesAndroid local databases
Android local databases
 
iOS Application Penetration Testing for Beginners
iOS Application Penetration Testing for BeginnersiOS Application Penetration Testing for Beginners
iOS Application Penetration Testing for Beginners
 
iOS Beginners Lesson 3
iOS Beginners Lesson 3iOS Beginners Lesson 3
iOS Beginners Lesson 3
 
Corporate-informatica-training-in-mumbai
Corporate-informatica-training-in-mumbaiCorporate-informatica-training-in-mumbai
Corporate-informatica-training-in-mumbai
 
Corporate-informatica-training-in-mumbai
Corporate-informatica-training-in-mumbaiCorporate-informatica-training-in-mumbai
Corporate-informatica-training-in-mumbai
 
CNIT 121: 13 Investigating Mac OS X Systems
CNIT 121: 13 Investigating Mac OS X SystemsCNIT 121: 13 Investigating Mac OS X Systems
CNIT 121: 13 Investigating Mac OS X Systems
 
Codeigniter Training Part3
Codeigniter Training Part3Codeigniter Training Part3
Codeigniter Training Part3
 
CS3270 - DATABASE SYSTEM - Lecture (1)
CS3270 - DATABASE SYSTEM -  Lecture (1)CS3270 - DATABASE SYSTEM -  Lecture (1)
CS3270 - DATABASE SYSTEM - Lecture (1)
 
ASP.NET Session 7
ASP.NET Session 7ASP.NET Session 7
ASP.NET Session 7
 
Information Retrieval - Data Science Bootcamp
Information Retrieval - Data Science BootcampInformation Retrieval - Data Science Bootcamp
Information Retrieval - Data Science Bootcamp
 
Linux System Programming - File I/O
Linux System Programming - File I/O Linux System Programming - File I/O
Linux System Programming - File I/O
 
Solr Recipes Workshop
Solr Recipes WorkshopSolr Recipes Workshop
Solr Recipes Workshop
 
CNIT 152: 13 Investigating Mac OS X Systems
CNIT 152: 13 Investigating Mac OS X SystemsCNIT 152: 13 Investigating Mac OS X Systems
CNIT 152: 13 Investigating Mac OS X Systems
 
Android Training Ahmedabad , Android Course Ahmedabad, Android architecture
Android Training Ahmedabad , Android Course Ahmedabad, Android architectureAndroid Training Ahmedabad , Android Course Ahmedabad, Android architecture
Android Training Ahmedabad , Android Course Ahmedabad, Android architecture
 
Microsoft Offical Course 20410C_10
Microsoft Offical Course 20410C_10Microsoft Offical Course 20410C_10
Microsoft Offical Course 20410C_10
 

Storage 8

  • 1. STORAGE By: Michael T. Shrove CPE 490/590 Smartphone Programming University of Alabama Huntsville
  • 3. Storage Options • Android provides several options for you to save persistent application data. • The solution you choose depends on your specific needs, such as whether the data should be private to your application or accessible to other applications (and the user) and how much space your data requires.
  • 4. Storage Options • Your data storage options are the following: • Shared Preferences • Store private primitive data in key-value pairs. • Internal Storage • Store private data on the device memory. • External Storage • Store public data on the shared external storage. • SQLite Databases • Store structured data in a private database. • Network Connection • Store data on the web with your own network server.
  • 5. Using Shared Preferences • The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. • You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. • This data will persist across user sessions (even if your application is killed). • Android provides the SharedPreferences object to help you save simple application data. • You may need to save to a file if your preferences are more complicated than normal.
  • 6. Getting Shared Preferences • To get a SharedPreferences object for your application, use one of two methods: • getSharedPreferences() • Use this if you need multiple preferences files identified by name, which you specify with the first parameter. • getPreferences() • Use this if you need only one preferences file for your Activity. • Because this will be the only preferences file for your Activity, you don't supply a name.
  • 7. Read and Write to Preferences • To write values: • Call edit() to get a SharedPreferences.Editor. • Add values with methods such as putBoolean() and putString(). • Commit the new values with commit() • To read values: • Use SharedPreferences methods such as getBoolean() and getString().
  • 9. Easier Way to Get Preferences
  • 10. Using Internal Storage • You can save files directly on the device's internal storage. • By default, files saved to the internal storage are private to your application and other applications cannot access them (nor can the user). • When the user uninstalls your application, these files are removed.
  • 11. Internal Storage Steps • To create and write a private file to the internal storage: • Call openFileOutput() with the name of the file and the operating mode. This returns a FileOutputStream. • Write to the file with write(). • Close the stream with close().
  • 12. Example • MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to your application. • Other modes available are: MODE_APPEND, MODE_WORLD_READABLE, and MODE_WORLD_WRITEABLE.
  • 13. Example Writing using OutputStreamWriter
  • 14. Read from Internal Storage • To read a file from internal storage: • Call openFileInput() and pass it the name of the file to read. This returns a FileInputStream. • Read bytes from the file with read() • Then close the stream with close()
  • 16. Saving Cache Files • If you'd like to cache some data, rather than store it persistently, you should use getCacheDir() • This will open a File that represents the internal directory where your application should save temporary cache files. • When the device is low on internal storage space, Android may delete these cache files to recover space. • However, you should not rely on the system to clean up these files for you. • You should always maintain the cache files yourself and stay within a reasonable limit of space consumed, such as 1MB. • When the user uninstalls your application, these files are removed.
  • 17. Other Useful Methods • getFilesDir() • Gets the absolute path to the filesystem directory where your internal files are saved. • getDir() • Creates (or opens an existing) directory within your internal storage space. • deleteFile() • Deletes a file saved on the internal storage. • fileList() • Returns an array of files currently saved by your application.
  • 18. External Storage • Every Android-compatible device supports a shared "external storage" that you can use to save files. • This can be a removable storage media (such as an SD card) or an internal (non-removable) storage. • Files saved to the external storage are world-readable and can be modified by the user when they enable USB mass storage to transfer files on a computer.
  • 19. Saving files that can be shared with other apps • Generally, new files that the user may acquire through your app should be saved to a "public" location on the device where other apps can access them and the user can easily copy them from the device. • When doing so, you should use to one of the shared public directories, such as Music/, Pictures/, and Ringtones/.
  • 20. Caution on External Storage • External storage can become unavailable if the user mounts the external storage on a computer or removes the media, and there's no security enforced upon files you save to the external storage. • All applications can read and write files placed on the external storage and the user can remove them.
  • 21. Getting Access to External Storage • In order to read or write files on the external storage, your app must acquire the READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE system permissions. • For example: • Note: If you need to both read and write files, then you need to request only the WRITE_EXTERNAL_STORAGE permission, because it implicitly requires read access as well.
  • 24. Using Databases • Android provides full support for SQLite databases. • Any databases you create will be accessible by name to any class in the application, but not outside the application. • The recommended method to create a new SQLite database is to create a subclass of SQLiteOpenHelper and override the onCreate() method, in which you can execute a SQLite command to create tables in the database.
  • 25. SQLite • Like iOS, Android also uses SQLite for databases. • Use SQL statements in order to create databases in the file system. • Can create databases on SD card or internal space. • If database is create on internal memory, it can be located at: • /data/data/<package_name>/databases/ folder
  • 26. DBAdapter Helper Class • A good practice when dealing with database in Android is to built a helper class. • Usually inside the helper class is a class called DBAdapter which also helps with the database code. • Keeps the complex algorithms dealing with databases in one class. • Custom class.
  • 27. Database Helper Class • Android created class. • Extends the SQLOpenHelper • Used to create the database if not there. • Used to upgrade the databases if something has changed.
  • 29. Open and Close Database
  • 32. Get Rows of Data
  • 36. IOS
  • 37. NSUserDefault • The NSUserDefaults class provides a programmatic interface for interacting with the defaults system. • The defaults system allows an application to customize its behavior to match a user’s preferences. • For example, you can allow users to determine what units of measurement your application displays or how often documents are automatically saved. • Applications record such preferences by assigning values to a set of parameters in a user’s defaults database. • The parameters are referred to as defaults since they’re commonly used to determine an application’s default state at startup or the way it acts by default.
  • 38. NSUserDefaults • At runtime, you use an NSUserDefaults object to read the defaults that your application uses from a user’s defaults database. • NSUserDefaults caches the information to avoid having to open the user’s defaults database each time you need a default value. • The synchronize method, which is automatically invoked at periodic intervals, keeps the in-memory cache in sync with a user’s defaults database.
  • 39. NSUserDefaults Supported Variable Types • NSData • String • NSNumber • UInt • Int • Float • Double • Bool • NSDate • Array • Dictionary
  • 40. Example of Writing to NSUserDefaults
  • 41. Sample Methods in NSUserDefaults • There are several convenience methods for storing data in NSUserDefaults they include: • func setBool(value: Bool, forKey defaultName: String) • func setInteger(value: Int, forKey defaultName: String) • func setFloat(value: Float, forKey defaultName: String) • func setDouble(value: Double, forKey defaultName: String) • func setObject(value: AnyObject?, forKey defaultName: String) • func setURL(url: NSURL, forKey defaultName: String)
  • 42. Reading from NSUserDefaults • Reading is done in a very similar fashion. • You need to get a reference to the NSUserDefaults object, and then ask it for the value you want. • In the case of reading out the String we wrote in and printing it to the console, we would use the code:
  • 43. Sample Methods in NSUserDefaults • Much like writing to NSUserDefaults, there are several convenience methods for reading data back out, that are a bit more full featured than writing them: • func boolForKey(defaultName: String) -> Bool • func integerForKey(defaultName: String) -> Int • func floatForKey(defaultName: String) -> Float • func doubleForKey(defaultName: String) -> Double • func objectForKey(defaultName: String) -> AnyObject? • func URLForKey(defaultName: String) -> NSURL? • func dataForKey(defaultName: String) -> NSData? • func stringForKey(defaultName: String) -> String? • func stringArrayForKey(defaultName: String) -> [AnyObject]? • func arrayForKey(defaultName: String) -> [AnyObject]? • func dictionaryForKey(defaultName: String) -> [NSObject : AnyObject]?
  • 45. Usage of Files • When downloading data, instead of keeping all the data in memory, a more effective and memory-efficient method is to save them in a file. • Memory is minimum in mobile phones. • Saving to a file is also useful for data that you want to retrieve even after the app as shut down and restarted.
  • 46. Sandbox • An iOS app’s interactions with the file system are limited mostly to the directories inside the app’s sandbox. • During installation of a new app, the installer creates a number of containers for the app. • Each container has a specific role. The bundle container holds the app’s bundle, whereas the data container holds data for both the application and the user. • The data container is further divided into a number of directories that the app can use to sort and organize its data.
  • 47. Sandbox • Because it is in a sandbox, an app is generally prohibited from accessing or creating files outside its containers. • One exception to this rule occurs when an app uses public system interfaces to access things such as the user’s contacts or music.
  • 48. iOS Standard Directories • For security purposes, an iOS app has limited a number of places where it can write its data. • When an app is installed on a device (either from iTunes or the App Store), the system creates a number of containers for the app. • These containers represent the universe for that app and contain everything the app can access directly.
  • 49. iOS Standard Directories Directory Description AppName.app This is the app’s bundle. This directory contains the app and all of its resources. Documents/ Use this directory to store user-generated content. The contents of this directory can be made available to the user through file sharing; therefore, his directory should only contain files that you may wish to expose to the user. The contents of this directory are backed up by iTunes. Documents/Inbox Use this directory to access files that your app was asked to open by outside entities. Specifically, the Mail program places email attachments associated with your app in this directory. Document interaction controllers may also place files in it. Your app can read and delete files in this directory but cannot create new files or write to existing files.
  • 50. iOS Standard Directories Directory Description Library/ This is the top-level directory for any files that are not user data files. You typically put files in one of several standard subdirectories. iOS apps commonly use the Application Support and Caches subdirectories; however, you can create custom subdirectories. Use the Library subdirectories for any files you don’t want exposed to the user. Your app should not use these directories for user data files. The contents of the Library directory (with the exception of the Caches subdirectory) are backed up by iTunes. tmp/ Use this directory to write temporary files that do not need to persist between launches of your app. Your app should remove files from this directory when they are no longer needed; however, the system may purge this directory when your app is not running. The contents of this directory are not backed up by iTunes.
  • 51. FilePaths • Get the contents of file directory in the /Resources directory • Just replace /Resources with other directory path.
  • 52. Creating an NSFileManger instance • Before proceeding, first we need to recap the steps necessary to obtain a reference to the application’s NSFileManager instance. • As discussed in the previous chapter, the NSFileManager class contains a class method named defaultManager that is used to obtain a reference.
  • 53. Check for the Existence of a File • The NSFileManager class contains an instance method named fileExistsAtPath which checks whether a specified file already exists. • The method takes as an argument an NSString object containing the path to the file in question and returns a Boolean value indicating the presence or otherwise of the specified file:
  • 57. NSFileHandle • An NSFileHandle object can be created when opening a file for reading, writing or updating (in other words both reading and writing). • Having opened a file, it must subsequently be closed when we have finished working with it using the closeFile method. • If an attempt to open a file fails, for example because an attempt is made to open a non-existent file for reading, these methods return nil.
  • 59. NSFileHandle Offset • NSFileHandle objects maintain a pointer to the current position in a file. • This is referred to as the offset. When a file is first opened the offset is set to 0 (the beginning of the file). • This means that any read or write operations performed using the NSFileHandle instance methods will take place at offset 0 in the file. • To perform operations at different locations in a file (for example to append data to the end of the file) it is first necessary to seek to the required offset.
  • 61. Reading from File • Once a file has been opened and assigned a file handle, the contents of that file may be read from the current offset position. • The readDataOfLength method reads a specified number of bytes of data from the file starting at the current offset. • For example, the following code on the next slide reads 5 bytes of data from offset 10 in a file. • The data read is returned encapsulated in an NSData object:
  • 62. Example of Reading a File Alternatively, the readDataToEndOfFile method will read all the data in the file starting at the current offset and ending at the end of the file.
  • 63. Writing to File • The writeData method writes the data contained in an NSData object to the file starting at the location of the offset. • Note that this does not insert data but rather overwrites any existing data in the file at the corresponding location.
  • 64. Example of Writing Data to File
  • 66. FMDB • FMDB is an Objective-C wrapper around SQLite • Because swift is not Objective-C and SQLite was written using the C language, we have to use a wrapper. • Open Source Library • https://github.com/ccgus/fmdb
  • 70. References • http://www.theappguruz.com/tutorial/use-sqlite-database- swift/ • http://www.theappguruz.com/tutorial/use-sqlite-database- swift/ • https://github.com/ccgus/fmdb • http://www.techotopia.com/index.php/Swift_iOS_8_Datab ase_Implementation_using_SQLite • http://developer.android.com • http://developer.apple.com