SlideShare a Scribd company logo
Android	Jetpack		
Room	Persistence	Library
Huỳnh	Quang	Thảo	
Trusting	Social	
Google	Developer	Expert	on	Android
When	start	new	android	app	…
- Database:	
- Native	SQLite	
- ORM	wrapper	on	SQLite:	DBFlow	
- Different	database	engines:	Realm.
When	start	new	android	app	…
- 	Running	a	jobs:	
- AlarmManager	+	Broadcast	Receiver	
- Firebase	JobDispatcher	
- JobScheduler	
- GCMNetworkManager	
-
When	start	new	android	app	…
- Control	data	Slow	and	update	latest	data	on	UI.
When	start	new	android	app	…
- Control	data	Slow	and	update	latest	data	on	UI.	
- Loading	data:	
- Loading	data	from	network.	
- Loading	data	from	on-device	database.	
- Loading	data	from	multiple	sources.
Android Jetpack: Room persistence library
Android Jetpack: Room persistence library
Android	Architecture	Components
ViewModel
Live	Data
World	before	Room
-SQL	boiler	code	
-Migration	
-Testing
Solutions
GreenDAO
Realm
DBFlow
Why	Room
-provides	an	abstraction	layer	over	SQLite.
Why	Room
-provides	an	abstraction	layer	over	SQLite.	
-Provide	compile-time	checking	for	SQL	Statement.
Why	Room
-provides	an	abstraction	layer	over	SQLite.	
-Provide	compile-time	checking	for	SQL	Statement.	
-Detect	query	database	on	main	thread.
Why	Room
-provides	an	abstraction	layer	over	SQLite.	
-Provide	compile-time	checking	for	SQL	Statement.	
-Detect	query	database	on	main	thread.	
-Easier	for	testing	and	migration.
Room	Components
Entity
public class Word {
private String mWord;
public Word(String word) {this.mWord = word;}
public String getWord(){return this.mWord;}
}
Entity
@Entity(tableName = "word_table")
public class Word {
@PrimaryKey
@NonNull
@ColumnInfo(name = "word")
private String mWord;
public Word(String word) {this.mWord = word;}
public String getWord(){return this.mWord;}
}
Entity
-Support	database	constraints.	(unique	key,	primary	keys	…)
Entity
-Support	database	constraints.	(unique	key,	primary	keys	…)	
-Support	deSine	relationship	between	model.
Entity
-Support	database	constraints.	(unique	key,	primary	keys	…)	
-Support	deSine	relationship	between	model.	
-Can	ignore	derived	Sields.
Entity
-Support	database	constraints.	(unique	key,	primary	keys	…)	
-Support	deSine	relationship	between	model.	
-Can	ignore	derived	Sields.	
-Support	database	views.
DAO
@Dao
public interface WordDao {
@Insert
void insert(Word word);
@Query("DELETE FROM word_table")
void deleteAll();
@Query("SELECT * from word_table ORDER BY word ASC")
LiveData<List<Word>> getAllWords();
}
DAO
-Use	annotation	for	simple	actions	such	as	insert/delete/update
@Dao
public interface WordDao {
@Insert
void insert(Word word);
}
DAO
-Write	custom	query.
@Dao
public interface WordDao {
@Query("DELETE FROM word_table")
void deleteAll();
@Query("SELECT * from word_table ORDER BY word ASC")
LiveData<List<Word>> getAllWords();
}
DAO
-Check	query	at	compile	time.
DAO
-Check	query	at	compile	time.
DAO
-Return	LiveData	data.
@Dao
public interface WordDao {
@Query("SELECT * from word_table ORDER BY word ASC")
LiveData<List<Word>> getAllWords();
}
Room	Database
-Abstraction	over	SQLiteHelper.
@Database(entities = {Word.class}, version = 1)
public abstract class WordRoomDatabase extends RoomDatabase {
public abstract WordDao wordDao();
private static volatile WordRoomDatabase INSTANCE;
static WordRoomDatabase getDatabase(final Context context) {
if (INSTANCE == null) {
synchronized (WordRoomDatabase.class) {
if (INSTANCE == null) {
// Create database here
INSTANCE =
Room.databaseBuilder(context.getApplicationContext(),
WordRoomDatabase.class, "word_database")
.addCallback(sRoomDatabaseCallback)
.build();
}
}
}
return INSTANCE;
}
}
Room	Database
Sample	application
Codelab:	
https://codelabs.developers.google.com/codelabs/android-room-with-a-view/#0	
Code	demo:	
https://github.com/googlecodelabs/android-room-with-a-view
Android Jetpack: Room persistence library
WorkSlow
7	steps	to	to	Room
https://medium.com/androiddevelopers/7-steps-to-room-27a5fe5f99b2
Step	1:	Add	dependencies
dependencies {
// Room components
implementation "android.arch.persistence.room:runtime:$rootProject.roomVersion"
annotationProcessor "android.arch.persistence.room:compiler:$rootProject.roomVersion"
androidTestImplementation "android.arch.persistence.room:testing:$rootProject.roomVersion"
// Lifecycle components
implementation "android.arch.lifecycle:extensions:$rootProject.archLifecycleVersion"
annotationProcessor "android.arch.lifecycle:compiler:$rootProject.archLifecycleVersion"
}
build.gradle	(module	app)
Step	2:	Update	model	to	entity
@Entity(tableName = "word_table")
public class Word {
@PrimaryKey
@NonNull
@ColumnInfo(name = "word")
private String mWord;
public Word(String word) {this.mWord = word;}
public String getWord(){return this.mWord;}
}
Step	3:	Create	DAO
@Dao
public interface WordDao {
@Insert
void insert(Word word);
}
Step	3:	Create	DAO
@Dao
public interface WordDao {
@Insert
void insert(Word word);
@Query("DELETE FROM word_table")
void deleteAll();
@Query("SELECT * from word_table ORDER BY word ASC")
LiveData<List<Word>> getAllWords();
}
Step	4:	Create	Database
@Database(entities = {Word.class}, version = 1)
public abstract class WordRoomDatabase extends RoomDatabase {
}
Step	4:	Create	Database
@Database(entities = {Word.class}, version = 1)
public abstract class WordRoomDatabase extends RoomDatabase {
public abstract WordDao wordDao();
}
Step	4:	Create	Database
@Database(entities = {Word.class}, version = 1)
public abstract class WordRoomDatabase extends RoomDatabase {
public abstract WordDao wordDao();
private static volatile WordRoomDatabase INSTANCE;
static WordRoomDatabase getDatabase(final Context context) {
if (INSTANCE == null) {
synchronized (WordRoomDatabase.class) {
if (INSTANCE == null) {
// Create database here
INSTANCE =
Room.databaseBuilder(context.getApplicationContext(),
WordRoomDatabase.class, "word_database")
.addCallback(sRoomDatabaseCallback)
.build();
}
}
}
return INSTANCE;
}
}
Step	5:	Update	Repository
public class WordRepository {
private WordDao mWordDao;
private LiveData<List<Word>> mAllWords;
}
Step	5:	Update	Repository
public class WordRepository {
private WordDao mWordDao;
private LiveData<List<Word>> mAllWords;
public WordRepository(Application application) {
WordRoomDatabase db = WordRoomDatabase.getDatabase(application);
mWordDao = db.wordDao();
mAllWords = mWordDao.getAllWords();
}
public LiveData<List<Word>> getAllWords() {
return mAllWords;
}
public void insert(Word word) {
new insertAsyncTask(mWordDao).execute(word);
}
}
Step	6:	Testing	DAO
@RunWith(AndroidJUnit4.class)
public class WordDaoTest {
private WordDao mWordDao;
private WordRoomDatabase mDb;
@Before
public void createDb() {
Context context = InstrumentationRegistry.getTargetContext();
mDb = Room.inMemoryDatabaseBuilder(context, WordRoomDatabase.class)
// Allowing main thread queries, just for testing.
.allowMainThreadQueries()
.build();
mWordDao = mDb.wordDao();
}
@After
public void closeDb() {
mDb.close();
}
}
Step	6:	Testing	DAO
@RunWith(AndroidJUnit4.class)
public class WordDaoTest {
private WordDao mWordDao;
private WordRoomDatabase mDb;
@Before
public void createDb() {
Context context = InstrumentationRegistry.getTargetContext();
mDb = Room.inMemoryDatabaseBuilder(context, WordRoomDatabase.class)
// Allowing main thread queries, just for testing.
.allowMainThreadQueries()
.build();
mWordDao = mDb.wordDao();
}
@After
public void closeDb() {
mDb.close();
}
@Test
public void insertAndGetWord() throws Exception {
Word word = new Word("word");
mWordDao.insert(word);
List<Word> allWords = LiveDataTestUtil.getValue
(mWordDao.getAlphabetizedWords());
assertEquals(allWords.get(0).getWord(), word.getWord());
}
}
Step	7:	Clean	up
- Remove	unused	classes	replaced	by	Room.	(i.e:	any	class	extends	SQLiteHelper)	
- More	complex	project:	
- https://medium.com/androiddevelopers/incrementally-migrate-from-sqlite-to-room-66c2f655b377
Learning	References
Android	architecture	components	
-	https://developer.android.com/jetpack/docs/guide
Learning	References
Android	architecture	components	
-	https://developer.android.com/jetpack/docs/guide	
Android	LifeCycle	components	
- https://www.youtube.com/watch?v=5qlIPTDE274	
- https://developer.android.com/topic/libraries/architecture/lifecycle
Learning	References
Android	architecture	components	
-	https://developer.android.com/jetpack/docs/guide	
Android	LifeCycle	components	
- https://www.youtube.com/watch?v=5qlIPTDE274	
- https://developer.android.com/topic/libraries/architecture/lifecycle	
Android	LiveData	
-	https://www.youtube.com/watch?v=OMcDk2_4LSk	
-	https://developer.android.com/topic/libraries/architecture/livedata
Learning	References
Android	architecture	components	
-	https://developer.android.com/jetpack/docs/guide	
Android	LifeCycle	components	
- https://www.youtube.com/watch?v=5qlIPTDE274	
- https://developer.android.com/topic/libraries/architecture/lifecycle	
Android	LiveData	
-	https://www.youtube.com/watch?v=OMcDk2_4LSk	
-	https://developer.android.com/topic/libraries/architecture/livedata	
Room	Persistence	libraries	
-	https://developer.android.com/topic/libraries/architecture/room	
-	https://www.youtube.com/watch?v=SKWh4ckvFPM
Learning	References
Android	architecture	components	
-	https://developer.android.com/jetpack/docs/guide	
Android	LifeCycle	components	
- https://www.youtube.com/watch?v=5qlIPTDE274	
- https://developer.android.com/topic/libraries/architecture/lifecycle	
Android	LiveData	
-	https://www.youtube.com/watch?v=OMcDk2_4LSk	
-	https://developer.android.com/topic/libraries/architecture/livedata	
Room	Persistence	libraries	
-	https://developer.android.com/topic/libraries/architecture/room	
-	https://www.youtube.com/watch?v=SKWh4ckvFPM	
Paging	
-	https://developer.android.com/topic/libraries/architecture/paging/
Codelab
- https://codelabs.developers.google.com/codelabs/android-lifecycles/#1	
- https://codelabs.developers.google.com/codelabs/android-persistence/#0	
- https://codelabs.developers.google.com/codelabs/android-room-with-a-view/#0	
- https://codelabs.developers.google.com/codelabs/android-paging/#0
Q&A

More Related Content

PDF
Short intro to scala and the play framework
PDF
Play Framework: async I/O with Java and Scala
PPTX
Full stack development with node and NoSQL - All Things Open - October 2017
PPT
Step-by-Step Introduction to Apache Flink
PPTX
Apache Flink Hands On
PPTX
Oracle Database on Docker - Best Practices
PPT
Apache Flink Crash Course by Slim Baltagi and Srini Palthepu
PDF
12 Things about Oracle WebLogic Server 12c
Short intro to scala and the play framework
Play Framework: async I/O with Java and Scala
Full stack development with node and NoSQL - All Things Open - October 2017
Step-by-Step Introduction to Apache Flink
Apache Flink Hands On
Oracle Database on Docker - Best Practices
Apache Flink Crash Course by Slim Baltagi and Srini Palthepu
12 Things about Oracle WebLogic Server 12c

What's hot (20)

PDF
SQL Track: Restoring databases with powershell
PDF
Leveraging Open Source for Database Development: Database Version Control wit...
PDF
Oracle WebLogic Server 12c with Docker
PDF
Which cloud provider for your oracle database
PPTX
Serhii Matynenko "How to Deal with Logs, Migrating from Monolith Architecture...
PDF
Take your database source code and data under control
PPTX
Python and Oracle : allies for best of data management
PPTX
Akka Actor presentation
PPTX
DNS for Developers - NDC Oslo 2016
PDF
Oracle Linux and Oracle Database - A Trusted Combination
PDF
Presto anatomy
PDF
Tanel Poder - Troubleshooting Complex Oracle Performance Issues - Part 1
PPTX
Real-Time Inverted Search NYC ASLUG Oct 2014
PPT
Spark stream - Kafka
PDF
OUG Ireland Meet-up 12th January
PDF
Scaling Your Cache
PPTX
How to build your query engine in spark
PDF
Scala Days NYC 2016
PDF
Spark Summit 2014: Spark Job Server Talk
PDF
Getting started with Apollo Client and GraphQL
SQL Track: Restoring databases with powershell
Leveraging Open Source for Database Development: Database Version Control wit...
Oracle WebLogic Server 12c with Docker
Which cloud provider for your oracle database
Serhii Matynenko "How to Deal with Logs, Migrating from Monolith Architecture...
Take your database source code and data under control
Python and Oracle : allies for best of data management
Akka Actor presentation
DNS for Developers - NDC Oslo 2016
Oracle Linux and Oracle Database - A Trusted Combination
Presto anatomy
Tanel Poder - Troubleshooting Complex Oracle Performance Issues - Part 1
Real-Time Inverted Search NYC ASLUG Oct 2014
Spark stream - Kafka
OUG Ireland Meet-up 12th January
Scaling Your Cache
How to build your query engine in spark
Scala Days NYC 2016
Spark Summit 2014: Spark Job Server Talk
Getting started with Apollo Client and GraphQL
Ad

Similar to Android Jetpack: Room persistence library (20)

PPTX
The Best Way to Become an Android Developer Expert with Android Jetpack
PDF
PDF
Spring.io
PDF
Native REST Web Services with Oracle 11g
PDF
[QE 2018] Adam Stasiak – Nadchodzi React Native – czyli o testowaniu mobilnyc...
PDF
Gradleintroduction 111010130329-phpapp01
PDF
Gradle Introduction
PDF
Lecture 11 Firebase overview
ODP
RichFaces - Testing on Mobile Devices
PPT
Drupal 7 Deployment Using Apache Ant. Dmitriy Svetlichniy.
PDF
Plugin-based software design with Ruby and RubyGems
PPTX
Cloudbase.io MoSync Reload Course
PDF
What's New In Laravel 5
PPTX
Test Automation for NoSQL Databases
PDF
Introduction to Node js for beginners + game project
PDF
Cocoapods and Most common used library in Swift
PPTX
QA Fest 2018. Adam Stasiak. React Native is Coming – the story of hybrid mobi...
PDF
Firebase overview
PPTX
PDF
Having Fun with Play
The Best Way to Become an Android Developer Expert with Android Jetpack
Spring.io
Native REST Web Services with Oracle 11g
[QE 2018] Adam Stasiak – Nadchodzi React Native – czyli o testowaniu mobilnyc...
Gradleintroduction 111010130329-phpapp01
Gradle Introduction
Lecture 11 Firebase overview
RichFaces - Testing on Mobile Devices
Drupal 7 Deployment Using Apache Ant. Dmitriy Svetlichniy.
Plugin-based software design with Ruby and RubyGems
Cloudbase.io MoSync Reload Course
What's New In Laravel 5
Test Automation for NoSQL Databases
Introduction to Node js for beginners + game project
Cocoapods and Most common used library in Swift
QA Fest 2018. Adam Stasiak. React Native is Coming – the story of hybrid mobi...
Firebase overview
Having Fun with Play
Ad

More from Thao Huynh Quang (15)

PDF
2021-03-08-telegram-vs-signal.pdf
PDF
Consensus and Raft Algorithm in Distributed System
PDF
Consensus and Raft algorithm (Vietnamese version)
PDF
Kotlin Introduction with Android applications
PDF
Git Introduction with illustrations
PDF
Android Performance Tips
PDF
Kafka: All an engineer needs to know
PDF
Blockchain introduction
PDF
Concurrency pattern in Kotlin
PDF
Observability and its application
PDF
GraphQL in Android
PDF
Android GRPC
PDF
Android Reverse Engineering
PPTX
PPTX
android deep linking
2021-03-08-telegram-vs-signal.pdf
Consensus and Raft Algorithm in Distributed System
Consensus and Raft algorithm (Vietnamese version)
Kotlin Introduction with Android applications
Git Introduction with illustrations
Android Performance Tips
Kafka: All an engineer needs to know
Blockchain introduction
Concurrency pattern in Kotlin
Observability and its application
GraphQL in Android
Android GRPC
Android Reverse Engineering
android deep linking

Recently uploaded (20)

PPTX
sap open course for s4hana steps from ECC to s4
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Encapsulation theory and applications.pdf
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Electronic commerce courselecture one. Pdf
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
Programs and apps: productivity, graphics, security and other tools
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
DOCX
The AUB Centre for AI in Media Proposal.docx
sap open course for s4hana steps from ECC to s4
“AI and Expert System Decision Support & Business Intelligence Systems”
Review of recent advances in non-invasive hemoglobin estimation
Encapsulation theory and applications.pdf
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Electronic commerce courselecture one. Pdf
Spectral efficient network and resource selection model in 5G networks
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
The Rise and Fall of 3GPP – Time for a Sabbatical?
Programs and apps: productivity, graphics, security and other tools
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Mobile App Security Testing_ A Comprehensive Guide.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Advanced methodologies resolving dimensionality complications for autism neur...
Chapter 3 Spatial Domain Image Processing.pdf
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Encapsulation_ Review paper, used for researhc scholars
Network Security Unit 5.pdf for BCA BBA.
Diabetes mellitus diagnosis method based random forest with bat algorithm
The AUB Centre for AI in Media Proposal.docx

Android Jetpack: Room persistence library