SlideShare une entreprise Scribd logo
1  sur  48
Persistence
Ilio Catallo, Eleonora Ciceri – Politecnico di Milano
ilio.catallo@polimi.it, eleonora.ciceri@polimi.it
TakeNotes current state
¤ TakeNotes is able to add and delete to-do items
¤ However, when the application is closed, the list is
deleted, since items are not stored in persistent state
¤ Solution: use a database to store items
¤ Each time a to-do item is added to the list, it is stored in the
database too
¤ When the application is launched, the list is loaded from the
database
2
Persistence in Android
3
Android storage options
¤ Android provides several ways to store users and
application data:
¤ Shared Preferences
¤ Internal / External Storage
¤ Network Connections
¤ SQLite Databases
¤ Databases are particularly suited when storing large
amounts of the same structured data
4
Example: TakeNotes
# to-do item Text
1 Send an e-mail to T.A.’s
2 Deliver project specifications
3 Buy milk
5
¤ In TakeNotes, we need at least to store the text of each
to-do item in the list
Introducing SQLite
¤ SQLite is a SQL databaseengine
¤ It is implemented as a C library
¤ SQLite’s main features:
¤ Open-source
¤ Standard-compliant
¤ Lightweight
¤ Single-tier
¤ SQLite is natively supported in Android, and it provides a a
robust persistence layer over which you have total control
6
Setting up a database
¤ No database is automatically provided with the
application, If you want to use SQLite, you have to:
¤ Create your own database
¤ Create tables
¤ Populate it with data
¤ Any databases will be accessible by name to any class in
the application, but not outside the application
7
Persistence layer
8
Business logic layer vs.
persistence layer
¤ You do not want the business logic code to deal directly
with the problem of persisting data
9
Activity 3
Data
source
Activity 1
Activity 2
SQL statements
are scattered
everywhere in
the codebase
If you change the
relational model
you have to
change the code
everywhere
Business logic layer vs.
persistence layer
¤ It would be better have a central authority responsible for
persisting the data
¤ The business logic can interact with such a central authority,
without caring of how the data are actually persisted
10
Central
authority
(repository)
Data
source
Activity 1
Activity 2
Activity 3
Businesslayer
The Repository pattern
¤ Since the central authority is usually referred to as the
repository, the resulting design pattern is called the
Repository pattern
¤ The repository act as a mediator between the business
logic layer and the data source layer
¤ The repository is usually implemented as a helper class
whose methods will be invoked by the business layer
code
11
The SQLite repository class
¤ The recommended method to create a new SQLite
database is to create a subclass of SQLiteOpenHelper
¤ SQLiteOpenHelper is the repository class that manages
interactions with the database
¤ The subclass of SQLiteOpenHelper will:
¤ Take care of opening the database if it exists
¤ Create the database if it does not exist
¤ Upgrade the database if it is necessary
12
The SQLite repository class
¤ DatabaseHandler is the repository class for our
application
¤ It is obtained by extending the SQLiteOpenHelper class
provided by Android
13
Creating a database
14
Anatomy of a SQLite database
¤ SQLite databases are stored in the
/data/data/package_name/databases folder on your
device or emulator
¤ Each SQLite database is characterized by the following
properties:
¤ A human-readable name
¤ A version number
15
Creating databases
¤ If not already present, the database is created on disk
the first time the application tries to access the data
¤ The database is upgraded every time a mismatch
between version numbers is detected.
¤ Typical use case:
¤ As a new app update requires a change in the database
schema, the version number is increased
¤ The app detects the mismatch and upgrades the schema of
the locally stored database
16
Creatingdatabases
17
Application starts
DB
exists?
Create
the DB on
disk
No
Yes
Is version
number
the
same?
Yes
Upgrade
the DB on
disk
No
First access
Creating databases
¤ The create/upgrade lifecycle is implemented in the
repository class by means of three methods:
¤ The constructor
¤ The onCreate() method
¤ the onUpdate() method
18
Creatingdatabases
19
Application starts
DB
exists?onCreate()
No
Yes
Is version
number
the
same?
Yes
onUpgrade()
No
First access
DatabaseHandler()
Overriding the constructor
¤ The repository class’ constructor informs the system that
the application wants to create a database
¤ Together with other parameters, it specifies:
¤ The name of the database
¤ The current version number
20
Overriding the constructor
21
Constants are
usually stored as
static data
members
The Context object is
needed to actually
create the database
(see reference)
An optional
CursorFactory,
typically just pass null
Overriding the onCreate()
method
¤ The onCreate() method is called when the database is
created for the first time
¤ The method is responsible for the creation of tables
¤ Remember: the method will not be called if no operation
is performed on the database
22
Overriding the onCreate()
method
23
a new table
named todo is
createdthe execSQL() method
works for any SQL that
does not return a result
Overriding the onUpgrade()
method
¤ The onUpgrade() method upgrades the existing
database to conform to the new version
¤ This method should drop tables, add tables, or do
anything else it needs to upgrade to the new schema
version
¤ Remember: the method will not be called if no operation
is performed on the database
24
Overriding the onUpgrade()
method
25
Snippet taken from:
http://stackoverflow.com/a/8133640/1849221
The database is upgraded from
oldVersion to newVersion by
cascading upgrade statement
Overriding the onUpgrade()
method
¤ The simplest upgrading policy is to drop the old table and
create a new one
26
The todo table is
droppedThe todo table is
created from
scratch
Obtaining the database
¤ To access a database using the repository class, call:
¤ getReadableDatabase() to obtain a read-only instance of
the database
¤ getWritableDatabase() to obtain a read-write instance of
the database
¤ After invoking one of the two methods:
¤ If the DB does not exist, onCreate() will be called
¤ If the DB needs to be upgraded, onUpgrade() will be called
27
Creatingdatabases
28
Application starts
DB
exists?
onCreate()
No
Yes
Is version
number
the
same?
Yes
onUpgrade()
No
First access
DatabaseHandler()
getWritableDatabase()
Interacting with the database
29
Object model vs.
Relational model
¤ The data you want to persist are usually encoded as class
instances, i.e., as objects
¤ Example: starting from TakeNotes v4, the to-do items are
modeled as instances of a ToDo class
30
Object model vs.
Relational model
¤ On the other hand, relation databases organize
information as tables and rows
¤ Example: the database for TakeNotes v4 can be made
of just one table named todo
31
# to-do item Text
1 Send an e-mail to T.A.’s
2 Deliver project specifications
3 Buy milk
Object-Relational Mapping
¤ As such:
¤ The business logic code deals with classes and objects
¤ The database deals with tables and rows
¤ We need a mediator to manage the automatic
transformation of objects to tuples and vice versa
¤ The technique of mapping objects to tuples (and vice
versa) is known as object-relational mapping (ORM)
32
Object-Relational Mapping
¤ A possible solution is to make the repository responsible of
providing a object-relation mapping (ORM) mechanism
33
Central
authority
(repository)
Data
source
Activity 1
Activity 2
Activity 3
Businesslayer
Java objects Tables and rows
Object-Relational Mapping
¤ The issue of mapping objects to tuples is a non-trivial one
¤ Developers spend effort in writing lots of code to convert row
and column data into objects
¤ Android put the entire burden on the developers
¤ It is up to the developer to correctly perform the mapping
¤ Third-party libraries are available
34
Writing data into the database
¤ The repository class should expose methods to persist
objects into the database
¤ Example: In TakeNotes, business logic code can persist a
ToDo class instances by invoking the addToDo method on
the repository class instance
35
Transforming objects into tuples
¤ The repository class needs to convert objects into tuples
¤ Android represents tuples as ContentValues class
instances
36
not needed if the id
column is
auto-incremented
Transforming objects into tuples
¤ Once a tuple has been populated, it is ready to be
inserted into the database
37
Object-relational
mapping
The NULL value hack
¤ While permitted in SQL, SQLite forbids to insert an empty
tuple, i.e., an empty ContentValues object
¤ If you pass an empty ContentValues to insert(), you
must also provide the name of a column that SQLite will
explicitly set to NULL
38
Name of the
column that
will be set to
NULL
just pass null if you
know that the
ContentValues is
not empty
Querying the database
¤ There exist two ways of querying the database:
¤ Use rawQuery() to execute a SQL statement directly
¤ use query() to build up a query from its component parts
39
Querying with rawQuery()
¤ The most immediate approach for querying the
database is to use rawQuery()
40
In case of parametric
queries, parameter
values must be
specified here
Querying with query()
¤ The query() method takes the discrete pieces of a
SELECT statement and builds the query from them.
¤ The pieces are:
¤ the name of the table to query against
¤ The list of columns to retrieve
¤ The WHERE clause (with possible positional parameters)
¤ The positional parameter values
¤ The GROUP BY clause, if any
¤ The HAVING clause, if any
¤ The ORDER BY clause, if any
41
Querying with query()
42
SELECT *
FROM todo
WHERE id=1 OR id=2
ORDER BY
clause
HAVING
clause
GROUP BY
clause
equivalent to
SELECT *
The result set
¤ A query result set are returned as a Cursor object
¤ A Cursor contains method for iterating over results
¤ With a Cursor you can:
¤ Find how many rows are in the result set via getCount()
¤ Iterate over the tuples via moveToFirst(), moveToNext()
and isAfterLast()
¤ Re-execute the query that created the cursor via requery()
¤ Release the cursor’s resources via close()
43
Result sets as lists of objects
¤ The repository class is responsible for transforming tuples in
the result set into a list of objects
¤ The repository class exposes methods that return
collection of objects
44
Result sets as lists of objects
45
Object-relational
mapping
References
46
References
¤ Reto Meier, Professional Android 4 Application
development 3rd Ed., Wrox
¤ SQLiteOpenHelper class reference:
http://developer.android.com/reference/android/datab
ase/sqlite/SQLiteOpenHelper.html
¤ SQLiteDatabase class reference:
http://developer.android.com/reference/android/datab
ase/sqlite/SQLiteDatabase.html
47
References
¤ Android API Guides, Storage Options
http://developer.android.com/guide/topics/data/data-
storage.html
¤ Android SQLite Database Tutorial:
http://www.androidhive.info/2011/11/android-sqlite-database-
tutorial/
¤ MSDN, the Repository pattern
http://msdn.microsoft.com/en-us/library/ff649690.aspx
¤ Martin Fowler, The Repository pattern
http://martinfowler.com/eaaCatalog/repository.html
48

Contenu connexe

Tendances (20)

For Beginners - Ado.net
For Beginners - Ado.netFor Beginners - Ado.net
For Beginners - Ado.net
 
Intake 38 10
Intake 38 10Intake 38 10
Intake 38 10
 
Ado.net
Ado.netAdo.net
Ado.net
 
Chapter 15
Chapter 15Chapter 15
Chapter 15
 
Chapter 3: ado.net
Chapter 3: ado.netChapter 3: ado.net
Chapter 3: ado.net
 
ADO.NET by ASP.NET Development Company in india
ADO.NET by ASP.NET  Development Company in indiaADO.NET by ASP.NET  Development Company in india
ADO.NET by ASP.NET Development Company in india
 
ADO .Net
ADO .Net ADO .Net
ADO .Net
 
Architectural anti-patterns for data handling
Architectural anti-patterns for data handlingArchitectural anti-patterns for data handling
Architectural anti-patterns for data handling
 
Ado.net
Ado.netAdo.net
Ado.net
 
ADO.NET -database connection
ADO.NET -database connectionADO.NET -database connection
ADO.NET -database connection
 
ASP.NET 09 - ADO.NET
ASP.NET 09 - ADO.NETASP.NET 09 - ADO.NET
ASP.NET 09 - ADO.NET
 
Ado.net
Ado.netAdo.net
Ado.net
 
ado.net
ado.netado.net
ado.net
 
ADO.NET
ADO.NETADO.NET
ADO.NET
 
Database Connection
Database ConnectionDatabase Connection
Database Connection
 
Ado .net
Ado .netAdo .net
Ado .net
 
Apache storm
Apache stormApache storm
Apache storm
 
Physical architecture of sql server
Physical architecture of sql serverPhysical architecture of sql server
Physical architecture of sql server
 
Apache Hive
Apache HiveApache Hive
Apache Hive
 
Sql Server Basics
Sql Server BasicsSql Server Basics
Sql Server Basics
 

En vedette

Android custom listview
Android custom listviewAndroid custom listview
Android custom listviewparmistech
 
Persitance Data with sqlite
Persitance Data with sqlitePersitance Data with sqlite
Persitance Data with sqliteArif Huda
 
Better Data Persistence on Android
Better Data Persistence on AndroidBetter Data Persistence on Android
Better Data Persistence on AndroidEric Maxwell
 
SquiDB: a SQLite layer for Android - Jonathan Koren, Yahoo!
SquiDB: a SQLite layer for Android - Jonathan Koren, Yahoo!SquiDB: a SQLite layer for Android - Jonathan Koren, Yahoo!
SquiDB: a SQLite layer for Android - Jonathan Koren, Yahoo!DroidConTLV
 
Painless Persistence in a Disconnected World
Painless Persistence in a Disconnected WorldPainless Persistence in a Disconnected World
Painless Persistence in a Disconnected WorldChristian Melchior
 
Open Ldap Integration and Configuration with Lifray 6.2
Open Ldap Integration and Configuration with Lifray 6.2Open Ldap Integration and Configuration with Lifray 6.2
Open Ldap Integration and Configuration with Lifray 6.2Vinaykumar Hebballi
 
Android Life Cycle
Android Life CycleAndroid Life Cycle
Android Life Cyclemssaman
 
Effective SQLite For Android
Effective SQLite For AndroidEffective SQLite For Android
Effective SQLite For AndroidShinobu Okano
 
Android development - ListView & Adapter
Android development - ListView & AdapterAndroid development - ListView & Adapter
Android development - ListView & AdapterLope Emano
 
Android life cycle
Android life cycleAndroid life cycle
Android life cycle瑋琮 林
 
Android lifecycle
Android lifecycleAndroid lifecycle
Android lifecycleKumar
 
android sqlite
android sqliteandroid sqlite
android sqliteDeepa Rani
 
Introduction to Listview in Android
Introduction to Listview in AndroidIntroduction to Listview in Android
Introduction to Listview in Androidtechnoguff
 
ListView and Custom ListView on Android Development [Thai]
ListView and Custom ListView on Android Development [Thai]ListView and Custom ListView on Android Development [Thai]
ListView and Custom ListView on Android Development [Thai]Somkiat Khitwongwattana
 

En vedette (20)

Android custom listview
Android custom listviewAndroid custom listview
Android custom listview
 
Android Data Persistence
Android Data PersistenceAndroid Data Persistence
Android Data Persistence
 
Persitance Data with sqlite
Persitance Data with sqlitePersitance Data with sqlite
Persitance Data with sqlite
 
Better Data Persistence on Android
Better Data Persistence on AndroidBetter Data Persistence on Android
Better Data Persistence on Android
 
SquiDB: a SQLite layer for Android - Jonathan Koren, Yahoo!
SquiDB: a SQLite layer for Android - Jonathan Koren, Yahoo!SquiDB: a SQLite layer for Android - Jonathan Koren, Yahoo!
SquiDB: a SQLite layer for Android - Jonathan Koren, Yahoo!
 
Android Custom view
Android Custom view Android Custom view
Android Custom view
 
Painless Persistence in a Disconnected World
Painless Persistence in a Disconnected WorldPainless Persistence in a Disconnected World
Painless Persistence in a Disconnected World
 
Google android Activity lifecycle
Google android Activity lifecycle Google android Activity lifecycle
Google android Activity lifecycle
 
Open Ldap Integration and Configuration with Lifray 6.2
Open Ldap Integration and Configuration with Lifray 6.2Open Ldap Integration and Configuration with Lifray 6.2
Open Ldap Integration and Configuration with Lifray 6.2
 
ANDROID USING SQLITE DATABASE ADMINISTRATORS ~HMFTJ
ANDROID USING SQLITE DATABASE ADMINISTRATORS ~HMFTJANDROID USING SQLITE DATABASE ADMINISTRATORS ~HMFTJ
ANDROID USING SQLITE DATABASE ADMINISTRATORS ~HMFTJ
 
Json vs Gson vs Jackson
Json vs Gson vs JacksonJson vs Gson vs Jackson
Json vs Gson vs Jackson
 
Android Life Cycle
Android Life CycleAndroid Life Cycle
Android Life Cycle
 
Effective SQLite For Android
Effective SQLite For AndroidEffective SQLite For Android
Effective SQLite For Android
 
Android development - ListView & Adapter
Android development - ListView & AdapterAndroid development - ListView & Adapter
Android development - ListView & Adapter
 
Aula 06 - TEP - Introdução SQLite
Aula 06 - TEP - Introdução SQLiteAula 06 - TEP - Introdução SQLite
Aula 06 - TEP - Introdução SQLite
 
Android life cycle
Android life cycleAndroid life cycle
Android life cycle
 
Android lifecycle
Android lifecycleAndroid lifecycle
Android lifecycle
 
android sqlite
android sqliteandroid sqlite
android sqlite
 
Introduction to Listview in Android
Introduction to Listview in AndroidIntroduction to Listview in Android
Introduction to Listview in Android
 
ListView and Custom ListView on Android Development [Thai]
ListView and Custom ListView on Android Development [Thai]ListView and Custom ListView on Android Development [Thai]
ListView and Custom ListView on Android Development [Thai]
 

Similaire à Persistence in Android

Not Your Father's Database by Databricks
Not Your Father's Database by DatabricksNot Your Father's Database by Databricks
Not Your Father's Database by DatabricksCaserta
 
Object Oriented Programming with Laravel - Session 6
Object Oriented Programming with Laravel - Session 6Object Oriented Programming with Laravel - Session 6
Object Oriented Programming with Laravel - Session 6Shahrzad Peyman
 
Vb.net session 16
Vb.net session 16Vb.net session 16
Vb.net session 16Niit Care
 
Not your Father's Database: Not Your Father’s Database: How to Use Apache® Sp...
Not your Father's Database: Not Your Father’s Database: How to Use Apache® Sp...Not your Father's Database: Not Your Father’s Database: How to Use Apache® Sp...
Not your Father's Database: Not Your Father’s Database: How to Use Apache® Sp...Databricks
 
OSA Con 2022 - Extract, Transform, and Learn about your developers - Brian Le...
OSA Con 2022 - Extract, Transform, and Learn about your developers - Brian Le...OSA Con 2022 - Extract, Transform, and Learn about your developers - Brian Le...
OSA Con 2022 - Extract, Transform, and Learn about your developers - Brian Le...Altinity Ltd
 
Synapseindia dot net development chapter 8 asp dot net
Synapseindia dot net development  chapter 8 asp dot netSynapseindia dot net development  chapter 8 asp dot net
Synapseindia dot net development chapter 8 asp dot netSynapseindiappsdevelopment
 
Shshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptx
Shshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptxShshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptx
Shshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptx086ChintanPatel1
 
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISPMCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISPAli Shah
 
Tools and approaches for migrating big datasets to the cloud
Tools and approaches for migrating big datasets to the cloudTools and approaches for migrating big datasets to the cloud
Tools and approaches for migrating big datasets to the cloudDataWorks Summit
 
php databse handling
php databse handlingphp databse handling
php databse handlingkunj desai
 
DS-UNIT 1 FINAL (2).pptx
DS-UNIT 1 FINAL (2).pptxDS-UNIT 1 FINAL (2).pptx
DS-UNIT 1 FINAL (2).pptxprakashvs7
 
Data Structures_Introduction
Data Structures_IntroductionData Structures_Introduction
Data Structures_IntroductionThenmozhiK5
 
Not Your Father's Database: How to Use Apache Spark Properly in Your Big Data...
Not Your Father's Database: How to Use Apache Spark Properly in Your Big Data...Not Your Father's Database: How to Use Apache Spark Properly in Your Big Data...
Not Your Father's Database: How to Use Apache Spark Properly in Your Big Data...Databricks
 

Similaire à Persistence in Android (20)

Linq to sql
Linq to sqlLinq to sql
Linq to sql
 
Not Your Father's Database by Databricks
Not Your Father's Database by DatabricksNot Your Father's Database by Databricks
Not Your Father's Database by Databricks
 
Object Oriented Programming with Laravel - Session 6
Object Oriented Programming with Laravel - Session 6Object Oriented Programming with Laravel - Session 6
Object Oriented Programming with Laravel - Session 6
 
Vb.net session 16
Vb.net session 16Vb.net session 16
Vb.net session 16
 
[iOS] Data Storage
[iOS] Data Storage[iOS] Data Storage
[iOS] Data Storage
 
Not your Father's Database: Not Your Father’s Database: How to Use Apache® Sp...
Not your Father's Database: Not Your Father’s Database: How to Use Apache® Sp...Not your Father's Database: Not Your Father’s Database: How to Use Apache® Sp...
Not your Father's Database: Not Your Father’s Database: How to Use Apache® Sp...
 
OSA Con 2022 - Extract, Transform, and Learn about your developers - Brian Le...
OSA Con 2022 - Extract, Transform, and Learn about your developers - Brian Le...OSA Con 2022 - Extract, Transform, and Learn about your developers - Brian Le...
OSA Con 2022 - Extract, Transform, and Learn about your developers - Brian Le...
 
android ch5.pptx
android ch5.pptxandroid ch5.pptx
android ch5.pptx
 
Synapseindia dot net development chapter 8 asp dot net
Synapseindia dot net development  chapter 8 asp dot netSynapseindia dot net development  chapter 8 asp dot net
Synapseindia dot net development chapter 8 asp dot net
 
Entity framework
Entity frameworkEntity framework
Entity framework
 
Shshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptx
Shshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptxShshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptx
Shshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptx
 
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISPMCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
 
Tools and approaches for migrating big datasets to the cloud
Tools and approaches for migrating big datasets to the cloudTools and approaches for migrating big datasets to the cloud
Tools and approaches for migrating big datasets to the cloud
 
php databse handling
php databse handlingphp databse handling
php databse handling
 
DS-UNIT 1 FINAL (2).pptx
DS-UNIT 1 FINAL (2).pptxDS-UNIT 1 FINAL (2).pptx
DS-UNIT 1 FINAL (2).pptx
 
Data Structures_Introduction
Data Structures_IntroductionData Structures_Introduction
Data Structures_Introduction
 
Sql Lab 4 Essay
Sql Lab 4 EssaySql Lab 4 Essay
Sql Lab 4 Essay
 
Mongo db
Mongo dbMongo db
Mongo db
 
Ado
AdoAdo
Ado
 
Not Your Father's Database: How to Use Apache Spark Properly in Your Big Data...
Not Your Father's Database: How to Use Apache Spark Properly in Your Big Data...Not Your Father's Database: How to Use Apache Spark Properly in Your Big Data...
Not Your Father's Database: How to Use Apache Spark Properly in Your Big Data...
 

Plus de ma-polimi

Android activities & views
Android activities & viewsAndroid activities & views
Android activities & viewsma-polimi
 
Android resources
Android resourcesAndroid resources
Android resourcesma-polimi
 
Broadcast Receivers in Android
Broadcast Receivers in AndroidBroadcast Receivers in Android
Broadcast Receivers in Androidma-polimi
 
Intents in Android
Intents in AndroidIntents in Android
Intents in Androidma-polimi
 
Events and Listeners in Android
Events and Listeners in AndroidEvents and Listeners in Android
Events and Listeners in Androidma-polimi
 
Android Components & Manifest
Android Components & ManifestAndroid Components & Manifest
Android Components & Manifestma-polimi
 
Introduction To Android
Introduction To AndroidIntroduction To Android
Introduction To Androidma-polimi
 

Plus de ma-polimi (8)

Android activities & views
Android activities & viewsAndroid activities & views
Android activities & views
 
Android resources
Android resourcesAndroid resources
Android resources
 
Broadcast Receivers in Android
Broadcast Receivers in AndroidBroadcast Receivers in Android
Broadcast Receivers in Android
 
Intents in Android
Intents in AndroidIntents in Android
Intents in Android
 
Events and Listeners in Android
Events and Listeners in AndroidEvents and Listeners in Android
Events and Listeners in Android
 
Android Components & Manifest
Android Components & ManifestAndroid Components & Manifest
Android Components & Manifest
 
TakeNotes
TakeNotesTakeNotes
TakeNotes
 
Introduction To Android
Introduction To AndroidIntroduction To Android
Introduction To Android
 

Dernier

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Principled Technologies
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 

Dernier (20)

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 

Persistence in Android

  • 1. Persistence Ilio Catallo, Eleonora Ciceri – Politecnico di Milano ilio.catallo@polimi.it, eleonora.ciceri@polimi.it
  • 2. TakeNotes current state ¤ TakeNotes is able to add and delete to-do items ¤ However, when the application is closed, the list is deleted, since items are not stored in persistent state ¤ Solution: use a database to store items ¤ Each time a to-do item is added to the list, it is stored in the database too ¤ When the application is launched, the list is loaded from the database 2
  • 4. Android storage options ¤ Android provides several ways to store users and application data: ¤ Shared Preferences ¤ Internal / External Storage ¤ Network Connections ¤ SQLite Databases ¤ Databases are particularly suited when storing large amounts of the same structured data 4
  • 5. Example: TakeNotes # to-do item Text 1 Send an e-mail to T.A.’s 2 Deliver project specifications 3 Buy milk 5 ¤ In TakeNotes, we need at least to store the text of each to-do item in the list
  • 6. Introducing SQLite ¤ SQLite is a SQL databaseengine ¤ It is implemented as a C library ¤ SQLite’s main features: ¤ Open-source ¤ Standard-compliant ¤ Lightweight ¤ Single-tier ¤ SQLite is natively supported in Android, and it provides a a robust persistence layer over which you have total control 6
  • 7. Setting up a database ¤ No database is automatically provided with the application, If you want to use SQLite, you have to: ¤ Create your own database ¤ Create tables ¤ Populate it with data ¤ Any databases will be accessible by name to any class in the application, but not outside the application 7
  • 9. Business logic layer vs. persistence layer ¤ You do not want the business logic code to deal directly with the problem of persisting data 9 Activity 3 Data source Activity 1 Activity 2 SQL statements are scattered everywhere in the codebase If you change the relational model you have to change the code everywhere
  • 10. Business logic layer vs. persistence layer ¤ It would be better have a central authority responsible for persisting the data ¤ The business logic can interact with such a central authority, without caring of how the data are actually persisted 10 Central authority (repository) Data source Activity 1 Activity 2 Activity 3 Businesslayer
  • 11. The Repository pattern ¤ Since the central authority is usually referred to as the repository, the resulting design pattern is called the Repository pattern ¤ The repository act as a mediator between the business logic layer and the data source layer ¤ The repository is usually implemented as a helper class whose methods will be invoked by the business layer code 11
  • 12. The SQLite repository class ¤ The recommended method to create a new SQLite database is to create a subclass of SQLiteOpenHelper ¤ SQLiteOpenHelper is the repository class that manages interactions with the database ¤ The subclass of SQLiteOpenHelper will: ¤ Take care of opening the database if it exists ¤ Create the database if it does not exist ¤ Upgrade the database if it is necessary 12
  • 13. The SQLite repository class ¤ DatabaseHandler is the repository class for our application ¤ It is obtained by extending the SQLiteOpenHelper class provided by Android 13
  • 15. Anatomy of a SQLite database ¤ SQLite databases are stored in the /data/data/package_name/databases folder on your device or emulator ¤ Each SQLite database is characterized by the following properties: ¤ A human-readable name ¤ A version number 15
  • 16. Creating databases ¤ If not already present, the database is created on disk the first time the application tries to access the data ¤ The database is upgraded every time a mismatch between version numbers is detected. ¤ Typical use case: ¤ As a new app update requires a change in the database schema, the version number is increased ¤ The app detects the mismatch and upgrades the schema of the locally stored database 16
  • 17. Creatingdatabases 17 Application starts DB exists? Create the DB on disk No Yes Is version number the same? Yes Upgrade the DB on disk No First access
  • 18. Creating databases ¤ The create/upgrade lifecycle is implemented in the repository class by means of three methods: ¤ The constructor ¤ The onCreate() method ¤ the onUpdate() method 18
  • 20. Overriding the constructor ¤ The repository class’ constructor informs the system that the application wants to create a database ¤ Together with other parameters, it specifies: ¤ The name of the database ¤ The current version number 20
  • 21. Overriding the constructor 21 Constants are usually stored as static data members The Context object is needed to actually create the database (see reference) An optional CursorFactory, typically just pass null
  • 22. Overriding the onCreate() method ¤ The onCreate() method is called when the database is created for the first time ¤ The method is responsible for the creation of tables ¤ Remember: the method will not be called if no operation is performed on the database 22
  • 23. Overriding the onCreate() method 23 a new table named todo is createdthe execSQL() method works for any SQL that does not return a result
  • 24. Overriding the onUpgrade() method ¤ The onUpgrade() method upgrades the existing database to conform to the new version ¤ This method should drop tables, add tables, or do anything else it needs to upgrade to the new schema version ¤ Remember: the method will not be called if no operation is performed on the database 24
  • 25. Overriding the onUpgrade() method 25 Snippet taken from: http://stackoverflow.com/a/8133640/1849221 The database is upgraded from oldVersion to newVersion by cascading upgrade statement
  • 26. Overriding the onUpgrade() method ¤ The simplest upgrading policy is to drop the old table and create a new one 26 The todo table is droppedThe todo table is created from scratch
  • 27. Obtaining the database ¤ To access a database using the repository class, call: ¤ getReadableDatabase() to obtain a read-only instance of the database ¤ getWritableDatabase() to obtain a read-write instance of the database ¤ After invoking one of the two methods: ¤ If the DB does not exist, onCreate() will be called ¤ If the DB needs to be upgraded, onUpgrade() will be called 27
  • 29. Interacting with the database 29
  • 30. Object model vs. Relational model ¤ The data you want to persist are usually encoded as class instances, i.e., as objects ¤ Example: starting from TakeNotes v4, the to-do items are modeled as instances of a ToDo class 30
  • 31. Object model vs. Relational model ¤ On the other hand, relation databases organize information as tables and rows ¤ Example: the database for TakeNotes v4 can be made of just one table named todo 31 # to-do item Text 1 Send an e-mail to T.A.’s 2 Deliver project specifications 3 Buy milk
  • 32. Object-Relational Mapping ¤ As such: ¤ The business logic code deals with classes and objects ¤ The database deals with tables and rows ¤ We need a mediator to manage the automatic transformation of objects to tuples and vice versa ¤ The technique of mapping objects to tuples (and vice versa) is known as object-relational mapping (ORM) 32
  • 33. Object-Relational Mapping ¤ A possible solution is to make the repository responsible of providing a object-relation mapping (ORM) mechanism 33 Central authority (repository) Data source Activity 1 Activity 2 Activity 3 Businesslayer Java objects Tables and rows
  • 34. Object-Relational Mapping ¤ The issue of mapping objects to tuples is a non-trivial one ¤ Developers spend effort in writing lots of code to convert row and column data into objects ¤ Android put the entire burden on the developers ¤ It is up to the developer to correctly perform the mapping ¤ Third-party libraries are available 34
  • 35. Writing data into the database ¤ The repository class should expose methods to persist objects into the database ¤ Example: In TakeNotes, business logic code can persist a ToDo class instances by invoking the addToDo method on the repository class instance 35
  • 36. Transforming objects into tuples ¤ The repository class needs to convert objects into tuples ¤ Android represents tuples as ContentValues class instances 36 not needed if the id column is auto-incremented
  • 37. Transforming objects into tuples ¤ Once a tuple has been populated, it is ready to be inserted into the database 37 Object-relational mapping
  • 38. The NULL value hack ¤ While permitted in SQL, SQLite forbids to insert an empty tuple, i.e., an empty ContentValues object ¤ If you pass an empty ContentValues to insert(), you must also provide the name of a column that SQLite will explicitly set to NULL 38 Name of the column that will be set to NULL just pass null if you know that the ContentValues is not empty
  • 39. Querying the database ¤ There exist two ways of querying the database: ¤ Use rawQuery() to execute a SQL statement directly ¤ use query() to build up a query from its component parts 39
  • 40. Querying with rawQuery() ¤ The most immediate approach for querying the database is to use rawQuery() 40 In case of parametric queries, parameter values must be specified here
  • 41. Querying with query() ¤ The query() method takes the discrete pieces of a SELECT statement and builds the query from them. ¤ The pieces are: ¤ the name of the table to query against ¤ The list of columns to retrieve ¤ The WHERE clause (with possible positional parameters) ¤ The positional parameter values ¤ The GROUP BY clause, if any ¤ The HAVING clause, if any ¤ The ORDER BY clause, if any 41
  • 42. Querying with query() 42 SELECT * FROM todo WHERE id=1 OR id=2 ORDER BY clause HAVING clause GROUP BY clause equivalent to SELECT *
  • 43. The result set ¤ A query result set are returned as a Cursor object ¤ A Cursor contains method for iterating over results ¤ With a Cursor you can: ¤ Find how many rows are in the result set via getCount() ¤ Iterate over the tuples via moveToFirst(), moveToNext() and isAfterLast() ¤ Re-execute the query that created the cursor via requery() ¤ Release the cursor’s resources via close() 43
  • 44. Result sets as lists of objects ¤ The repository class is responsible for transforming tuples in the result set into a list of objects ¤ The repository class exposes methods that return collection of objects 44
  • 45. Result sets as lists of objects 45 Object-relational mapping
  • 47. References ¤ Reto Meier, Professional Android 4 Application development 3rd Ed., Wrox ¤ SQLiteOpenHelper class reference: http://developer.android.com/reference/android/datab ase/sqlite/SQLiteOpenHelper.html ¤ SQLiteDatabase class reference: http://developer.android.com/reference/android/datab ase/sqlite/SQLiteDatabase.html 47
  • 48. References ¤ Android API Guides, Storage Options http://developer.android.com/guide/topics/data/data- storage.html ¤ Android SQLite Database Tutorial: http://www.androidhive.info/2011/11/android-sqlite-database- tutorial/ ¤ MSDN, the Repository pattern http://msdn.microsoft.com/en-us/library/ff649690.aspx ¤ Martin Fowler, The Repository pattern http://martinfowler.com/eaaCatalog/repository.html 48