70
STORAGE By: Michael T. Shrove CPE 490/590 Smartphone Programming University of Alabama Huntsville

Storage 8

Embed Size (px)

Citation preview

Page 1: Storage   8

STORAGEBy: Michael T. Shrove

CPE 490/590 Smartphone Programming

University of Alabama Huntsville

Page 2: Storage   8

ANDROID

Page 3: Storage   8

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.

Page 4: Storage   8

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.

Page 5: Storage   8

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.

Page 6: Storage   8

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.

Page 7: Storage   8

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().

Page 8: Storage   8

Example

Read

Write

Page 9: Storage   8

Easier Way to Get Preferences

Page 10: Storage   8

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.

Page 11: Storage   8

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().

Page 12: Storage   8

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.

Page 13: Storage   8

Example Writing using OutputStreamWriter

Page 14: Storage   8

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

Page 15: Storage   8

Example using InputStreamReader

Page 16: Storage   8

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.

Page 17: Storage   8

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.

Page 18: Storage   8

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.

Page 19: Storage   8

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/.

Page 20: Storage   8

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.

Page 21: Storage   8

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.

Page 22: Storage   8

Example

Page 23: Storage   8

Example

Page 24: Storage   8

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.

Page 25: Storage   8

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

Page 26: Storage   8

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.

Page 27: Storage   8

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.

Page 28: Storage   8

DBAdapter Beginnings

Page 29: Storage   8

Open and Close Database

Page 30: Storage   8

Insert Rows

Page 31: Storage   8

Delete Rows

Page 32: Storage   8

Get Rows of Data

Page 33: Storage   8

Update Rows

Page 34: Storage   8

Using the DBAdapter Class

Page 35: Storage   8

Using Cursor Object

Page 36: Storage   8

IOS

Page 37: Storage   8

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.

Page 38: Storage   8

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.

Page 39: Storage   8

NSUserDefaults Supported Variable Types

• NSData• String• NSNumber

• UInt• Int• Float• Double

• Bool• NSDate• Array• Dictionary

Page 40: Storage   8

Example of Writing to NSUserDefaults

Page 41: Storage   8

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)

Page 42: Storage   8

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:

Page 43: Storage   8

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]?

Page 44: Storage   8

File I/O

Page 45: Storage   8

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.

Page 46: Storage   8

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.

Page 47: Storage   8

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.

Page 48: Storage   8

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.

Page 49: Storage   8

iOS Standard DirectoriesDirectory 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.

Page 50: Storage   8

iOS Standard DirectoriesDirectory 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.

Page 51: Storage   8

FilePaths• Get the contents of file directory in the /Resources

directory• Just replace /Resources with other directory path.

Page 52: Storage   8

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.

Page 53: Storage   8

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:

Page 54: Storage   8

Moving/Rename a File

Page 55: Storage   8

Copying a File

Page 56: Storage   8

Removing a File

Page 57: Storage   8

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.

Page 58: Storage   8

Example of NSFileHandle

Page 59: Storage   8

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.

Page 60: Storage   8

NSFileHandle Offset

Page 61: Storage   8

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:

Page 62: Storage   8

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.

Page 63: Storage   8

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.

Page 64: Storage   8

Example of Writing Data to File

Page 65: Storage   8

Database

Page 66: Storage   8

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

Page 67: Storage   8

Open and Create

Page 68: Storage   8

Insert into Database

Page 69: Storage   8

Query from Database