datastorageand exchangein android -...
TRANSCRIPT
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
Data storage and exchange in AndroidMobile App Development
Przemyslaw Pawluk
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
1 IntroductionOverview
2 Shared Preferences
3 SQLite DatabaseSQLite – OverviewImplementation
4 Content ProvidersOverviewMethods to implementURI like SQL
5 File systemInternal storageExternal storage
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
Overview
1 IntroductionOverview
2 Shared Preferences
3 SQLite DatabaseSQLite – OverviewImplementation
4 Content ProvidersOverviewMethods to implementURI like SQL
5 File systemInternal storageExternal storage
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
Overview
Options we have
SharedPreferences
Implements named maps ofname/value pairs that can bepersisted across sessions andshared among applicationcomponents running within thesame application sandbox.
SQLite
Is a SQL implementation.
Content provider
An interface used betweenapplications. The serverapplication that hosts the datamanages it through basiccreate, read, update, anddelete (CRUD) operations.
Files
Local files stored in shared orapp specific space
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
Overview
Options we have
SharedPreferences
Implements named maps ofname/value pairs that can bepersisted across sessions andshared among applicationcomponents running within thesame application sandbox.
SQLite
Is a SQL implementation.
Content provider
An interface used betweenapplications. The serverapplication that hosts the datamanages it through basiccreate, read, update, anddelete (CRUD) operations.
Files
Local files stored in shared orapp specific space
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
Overview
Options we have
SharedPreferences
Implements named maps ofname/value pairs that can bepersisted across sessions andshared among applicationcomponents running within thesame application sandbox.
SQLite
Is a SQL implementation.
Content provider
An interface used betweenapplications. The serverapplication that hosts the datamanages it through basiccreate, read, update, anddelete (CRUD) operations.
Files
Local files stored in shared orapp specific space
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
Overview
Options we have
SharedPreferences
Implements named maps ofname/value pairs that can bepersisted across sessions andshared among applicationcomponents running within thesame application sandbox.
SQLite
Is a SQL implementation.
Content provider
An interface used betweenapplications. The serverapplication that hosts the datamanages it through basiccreate, read, update, anddelete (CRUD) operations.
Files
Local files stored in shared orapp specific space
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
1 IntroductionOverview
2 Shared Preferences
3 SQLite DatabaseSQLite – OverviewImplementation
4 Content ProvidersOverviewMethods to implementURI like SQL
5 File systemInternal storageExternal storage
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
Shared Preferences
How it works?
Shared Preferences are stored within the application’s sandbox, sothey can be shared between application’s components but aren’tavailable to other applications.
How to use it?
To modify a Shared Preference, use theSharedPreferences.Editor class. Get the Editor object bycalling edit on the Shared Preferences object you want to change.Use editor.putXXXX([name], [val]) to add preferences andeditor.getXXXX([name]) to retrieve.
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
Shared Preferences
How it works?
Shared Preferences are stored within the application’s sandbox, sothey can be shared between application’s components but aren’tavailable to other applications.
How to use it?
To modify a Shared Preference, use theSharedPreferences.Editor class. Get the Editor object bycalling edit on the Shared Preferences object you want to change.Use editor.putXXXX([name], [val]) to add preferences andeditor.getXXXX([name]) to retrieve.
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
User Preferences
Use built-in PreferencesActivity
Creating your own Activity to control user preferences is consideredbad practice. Android Studio provides you with a standard settingsscreen using the Settings Activity.
Question
Why is building custom settings activity a bad practice?
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
User Preferences
Use built-in PreferencesActivity
Creating your own Activity to control user preferences is consideredbad practice. Android Studio provides you with a standard settingsscreen using the Settings Activity.
Question
Why is building custom settings activity a bad practice?
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
SQLite – OverviewImplementation
1 IntroductionOverview
2 Shared Preferences
3 SQLite DatabaseSQLite – OverviewImplementation
4 Content ProvidersOverviewMethods to implementURI like SQL
5 File systemInternal storageExternal storage
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
SQLite – OverviewImplementation
SQLite
Android uses the SQLite database engine:
self-contained,
transactional,
requires no separate server process,
actively developed by a large community
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
SQLite – OverviewImplementation
What is SQLite?
SQLite is an international, open source project implementing atransactional, self-contained relational database.It is not a Google project, but Google has contributed to it.
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
SQLite – OverviewImplementation
How it is stored?
With SQLite, the database is a simple single disk file. All of thedata structures making up a relational databasetables, views,indexes, etc.are within this file.
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
SQLite – OverviewImplementation
Before we start
Good practices
It is a good practice to separate database specific code from therest of your application and encapsulate it in a single class. Otherclasses should use standard Java classes or Cursors and be unawareof how the data is actually stored.
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
SQLite – OverviewImplementation
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
SQLite – OverviewImplementation
Schema and Contract
Schema
A formal declaration of how the database is organized. Theschema is reflected in the SQL statements that you use to createyour database.
Contract
A companion class, which explicitly specifies the layout of yourschema in a systematic and self-documenting way.
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
SQLite – OverviewImplementation
Why do we need a Contract class?
A contract class is a container for constants that define namesfor URIs, tables, and columns. The contract class allows youto use the same constants across all the other classes in thesame package. This lets you change a column name in oneplace and have it propagate throughout your code.
A good way to organize a contract class is to put definitionsthat are global to your whole database in the root level of theclass. Then create an inner class for each table thatenumerates its columns.
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
SQLite – OverviewImplementation
Note:BaseColumns
Note
By implementing the BaseColumns interface, your inner class caninherit a primary key field called _ID that some Android classessuch as cursor adaptors will expect it to have. It’s not required,but this can help your database work harmoniously with theAndroid framework.
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
SQLite – OverviewImplementation
Example
1 p u b l i c f i n a l c l a s s FeedReaderCont rac t {2 // To p r e v en t someone from a c c i d e n t a l l y i n s t a n t i a t i n g
the c o n t r a c t c l a s s ,3 // g i v e i t an empty c o n s t r u c t o r .4 p u b l i c FeedReaderCont rac t ( ) {}5
6 /∗ I n n e r c l a s s t ha t d e f i n e s the t a b l e c on t en t s ∗/7 p u b l i c s t a t i c a b s t r a c t c l a s s FeedEntry implements
BaseColumns {8 p u b l i c s t a t i c f i n a l S t r i n g TABLE NAME = ” en t r y ” ;9 p u b l i c s t a t i c f i n a l S t r i n g COLUMN NAME ENTRY ID = ”
e n t r y i d ” ;10 p u b l i c s t a t i c f i n a l S t r i n g COLUMN NAME TITLE = ”
t i t l e ” ;11 p u b l i c s t a t i c f i n a l S t r i n g COLUMN NAME SUBTITLE = ”
s u b t i t l e ” ;12 . . .13 }14 }
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
SQLite – OverviewImplementation
Database interface
We will implement a class MyDatabaseManager serving as aninterface to the database. It extends the abstractSQLiteOpenHelper class, and therefore must override theonCreate and onUpgrade methods.
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
SQLite – OverviewImplementation
onCreate
Automatically called when the application starts for the first time;its job is to create the database
onUpgrade
Used to update a database on the phone when new version of theapplication is shipped
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
SQLite – OverviewImplementation
General elements of the class
Constants
DATABASE NAME – holds the filename of the database
DATABASE VERSION – defines the database version understoodby the software that defines the constant. If the version of thedatabase on the machine is less than DATABASE VERSION, theapplication should run onUpgrade
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
SQLite – OverviewImplementation
General elements of the class
Constructor
call constructor from super
store a context object (usually an activity that opens thedatabase)
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
SQLite – OverviewImplementation
onCreate
You can use two approaches to the implementation that are :
Embedded SQL
SQL commands are embeddedinto Java. The code is in asingle file
Separated SQL
SQL command are stored intoXML file strings.xml andrecalled when needed. Codedistributed among two(potentially more) files
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
SQLite – OverviewImplementation
Reading Data from the Database
Create an SQL statement that describes the data that youneed to retrieve.
Execute that statement against the database.
Map the resulting SQL data into data structures that thelanguage you’re working in can understand.
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
SQLite – OverviewImplementation
Better approach
Android offers slightly better approach – custom cursors.
Coursor
It is a class encapsulating a query results. Query returns a simplecursor, while custom cursor provides (in addition) methods dealingwith specific structure of the data
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
SQLite – OverviewImplementation
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
OverviewMethods to implementURI like SQL
1 IntroductionOverview
2 Shared Preferences
3 SQLite DatabaseSQLite – OverviewImplementation
4 Content ProvidersOverviewMethods to implementURI like SQL
5 File systemInternal storageExternal storage
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
OverviewMethods to implementURI like SQL
Content Provider – Overview
What is Content Provider
It is a mechanism enabling data sharing across applications. Ingeneral reading from other application is not allowed. Both readerand writer (producer/consumer) uses an API to provide or accessdata
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
OverviewMethods to implementURI like SQL
Nine steps to success
1 Extend the ContentProviderclass.
2 Define the CONTENT URI foryour content provider.
3 Create the data storage foryour content.
4 Create the column names forcommunication with clients.
5 Define the process by whichbinary data is returned to theclient.
6 Declare public static Stringsthat clients use to specifycolumns.
7 Implement the CRUD methodsof a Cursor to return to theclient.
8 Update theAndroidManifest.xml file todeclare your < provider >.
9 Define MIME types for anynew data types.
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
OverviewMethods to implementURI like SQL
onCreate
This method is called during the content provider’s startup. Anycode you want to run just once, such as making a databaseconnection, should reside in this method.
getType
This method, when given a URI, returns the MIME type of thedata that this content provider provides at that URI. The URIcomes from the client application interested in accessing the data.
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
OverviewMethods to implementURI like SQL
insert/create
This method is called when the client code wishes to insert datainto the database your content provider is serving. Normally, theimplementation for this method will either directly or indirectlyresult in a database insert operation.
query/read
This method is called whenever a client wishes to read data fromthe content provider’s database. It is normally called throughContentProvider’s managedQuery method. Normally, here youretrieve data using a SQL SELECT statement and return a cursorcontaining the requested data.
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
OverviewMethods to implementURI like SQL
update
This method is called when a client wishes to update one or morerows in the ContentProvider’s database. It translates to a SQLUPDATE statement.
delete
This method is called when a client wishes to delete one or morerows in the ContentProvider’s database. It translates to a SQLDELETE statement.
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
OverviewMethods to implementURI like SQL
URI
content://authority/path/id
where:
content:// is the standard required prefix.
authority is the name of the provider. Using your fullyqualified package name is recommended to prevent namecollisions.
path is a virtual directory within the provider that identifiesthe kind of data being requested.
id is the primary key of a specific record being requested. Torequest all records of a particular type, omit this and thetrailing slash.
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
OverviewMethods to implementURI like SQL
Default content provided by Android
content://browser
content://contacts
content://media
content://settings
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
OverviewMethods to implementURI like SQL
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
Internal storageExternal storage
1 IntroductionOverview
2 Shared Preferences
3 SQLite DatabaseSQLite – OverviewImplementation
4 Content ProvidersOverviewMethods to implementURI like SQL
5 File systemInternal storageExternal storage
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
Internal storageExternal storage
Storage types
Internal storage
It’s always available.
No special permissionrequired
Files saved here areaccessible by only your appby default.
When the user uninstallsyour app, the systemremoves all your app’s filesfrom internal storage.
External storage
It’s not always available(e.g. removed USB storageor SD card)
It’s world-readable, so filessaved here may be readoutside of your control.
When the user uninstallsyour app, the systemremoves your app’s files onlyfromgetExternalFilesDir().
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
Internal storageExternal storage
Which one should I choose?
Internal storage
Internal storage is best when youwant to be sure that neither theuser nor other apps can accessyour files.
External storage
External storage is the best placefor files that don’t require accessrestrictions and for files that youwant to share with other apps orallow the user to access with acomputer.
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
Internal storageExternal storage
Storage and App location
App installation
Although apps are installed onto the internal storage by default,you can specify the android:installLocation attribute in yourmanifest so your app may be installed on external storage. Usersappreciate this option when the APK size is very large and theyhave an external storage space that’s larger than the internalstorage.
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
Internal storageExternal storage
Required permissions for external
1 <uses−p e rm i s s i o n and ro i d : name=” and ro i d . p e rm i s s i o n .READ EXTERNAL STORAGE” />
1 <uses−p e rm i s s i o n and ro i d : name=” and ro i d . p e rm i s s i o n .WRITE EXTERNAL STORAGE” />
Note
You need only one of the above becauseWRITE_EXTERNAL_STORAGE implicitly gives you a READpermission.
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
Internal storageExternal storage
Internal Storage
Your app’s internal storage directory is specified by your app’spackage name in a special location of the Android file system.
Another app can read your internal files if you set the filemode to be readable but
Other apps cannot browse your internal directories and do nothave read or write access unless you explicitly set the files tobe readable or writable.
If you use MODE_PRIVATE for your files on the internalstorage, they are never accessible to other apps.
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
Internal storageExternal storage
Create a file
1 F i l e f i l e = new F i l e ( c on t e x t . g e t F i l e s D i r ( ) , f i l e n ame ) ;
Figure: Create empty file
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
Internal storageExternal storage
Create a file
1 S t r i n g f i l e n ame = ” my f i l e ” ;2 S t r i n g s t r i n g = ” He l l o wor ld ! ” ;3 F i l eOutputSt ream outputStream ;4 t r y {5 outputStream = openF i l eOutput ( f i l e name , Context .
MODE PRIVATE) ;6 outputStream . w r i t e ( s t r i n g . ge tBy te s ( ) ) ;7 outputStream . c l o s e ( ) ;8 } ca tch ( Excep t i on e ) {9 e . p r i n t S t a c kT r a c e ( ) ;
10 }
Figure: Alternatively, you can write to a file in your internal directoryusing a stream.
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
Internal storageExternal storage
Create a file
1 p u b l i c F i l e getTempFi le ( Context contex t , S t r i n g u r l ) {2 F i l e f i l e ;3 t r y {4 S t r i n g f i l eName = Ur i . p a r s e ( u r l ) . getLastPathSegment
( ) ;5 f i l e = F i l e . c r ea t eTempF i l e ( f i l eName , n u l l , c on t e x t .
ge tCacheDi r ( ) ) ;6 ca tch ( IOExcept i on e ) {7 // E r r o r wh i l e c r e a t i n g f i l e8 }9 r e t u r n f i l e ;
10 }
Figure: Create a temporary file e.g, to cache some data
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
Internal storageExternal storage
External storage
Because the external storage may be unavailable–such as when theuser has mounted the storage to a PC or has removed the SD cardthat provides the external storage–you should always verify thatthe volume is available before accessing it. You can query theexternal storage state
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
Internal storageExternal storage
Storage state
Checks if external storage is available to at least read
1 p u b l i c boo l ean i s E x t e r n a l S t o r a g eR e a d a b l e ( ) {2 S t r i n g s t a t e = Envi ronment . g e t E x t e r n a l S t o r a g e S t a t e ( ) ;3 i f ( Env i ronment .MEDIA MOUNTED. equa l s ( s t a t e ) | |4 Envi ronment .MEDIA MOUNTED READ ONLY. e qua l s ( s t a t e ) ) {5 r e t u r n t r u e ;6 }7 r e t u r n f a l s e ;8 }
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
Internal storageExternal storage
Storage state
Checks if external storage is available for read and write
1 p u b l i c boo l ean i s E x t e r n a l S t o r a g eW r i t a b l e ( ) {2 S t r i n g s t a t e = Envi ronment . g e t E x t e r n a l S t o r a g e S t a t e ( ) ;3 i f ( Env i ronment .MEDIA MOUNTED. equa l s ( s t a t e ) ) {4 r e t u r n t r u e ;5 }6 r e t u r n f a l s e ;7 }
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
Internal storageExternal storage
File management in exernal storage
Public files
Files that should be freelyavailable to other apps and to theuser. When the user uninstallsyour app, these files shouldremain available to the user.
photos
downloaded files
Private files
Files that rightfully belong toyour app and should be deletedwith the app. These files areaccessible by the user and otherapps but they are files that don’tprovide value to the user outsideyour app.
additional resources
temporary media files
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
Internal storageExternal storage
Query free space
Query
If you know ahead of time how much data you’re saving, you canfind out whether sufficient space is available without causing anIOException by calling getFreeSpace() or getTotalSpace()
Warning
The system does not guarantee that you can write as many bytesas are indicated by getFreeSpace().
Przemyslaw Pawluk Data storage and exchange in Android
OutlineIntroduction
Shared PreferencesSQLite Database
Content ProvidersFile system
Internal storageExternal storage
Przemyslaw Pawluk Data storage and exchange in Android