SlideShare a Scribd company logo
Room
Saving Data Using the Room
Persistence Library
• Room provides an abstraction layer over SQLite to allow
fluent database access while harnessing the full power of
SQLite.
• That way, when the device cannot access the network, the user can
still browse that content while they are offline. Any user-initiated
content changes are then synced to the server after the device is back
online.
3 major components in Room
Room architecture diagram
Entity Represents a table within the database.
Dao Contains the methods used for accessing the database.
Database
• Contains the database holder and serves as the main access point for the
underlying connection to your app's persisted, relational data. The class
that's annotated with @Database should satisfy the following conditions:
 Be an abstract class that extends RoomDatabase.
 Include the list of entities associated with the database within the
annotation.
 Contain an abstract method that has 0 arguments and returns the class
that is annotated with @Dao.
• At runtime, you can acquire an instance of Database by
calling Room.databaseBuilder() or Room.inMemoryDatabaseBuilder().
Note: You should follow the singleton design pattern when instantiating
an AppDatabase object, as each RoomDatabase instance is fairly expensive, and
you rarely need access to multiple instances.
After creating the files above, you get an instance of the created database
using the following code:
Caused by: java.lang.IllegalStateException: Cannot access database on the main
thread since it may potentially lock the UI for a long period of time.
Sol1.
Sol2.
RoomDatabase.java
Defining data using Room entities
• By default, Room creates a column for each field that's defined in the
entity. If an entity has fields that you don't want to persist, you can
annotate them using @Ignore. You must reference the entity class
through the entities array in the Database class.
Note: Entities can have either an empty constructor (if
the corresponding DAO class can access each persisted
field) or a constructor whose parameters contain types
and names that match those of the fields in the entity.
Room can also use full or partial constructors, such as a
constructor that receives only some of the fields.
Entity
• Each entity must define at least 1 field as a primary key. Even when there is
only 1 field, you still need to annotate the field with the
@PrimaryKey annotation. Also, if you want Room to assign automatic IDs to
entities, you can set the @PrimaryKey's autoGenerate property. If the entity
has a composite primary key, you can use the primaryKeys property of
the @Entity annotation, as shown in the following code snippet:
Use a primary key
Entity Annotate indices and uniqueness
Entity
• Room doesn’t allow object references
Define relationships between objects
Note: SQLite handles @Insert(onConflict = REPLACE) as a set
of REMOVE and REPLACE operations instead of a single UPDATE operation. This method of
replacing conflicting values could affect your foreign key constraints. For more details, see
the SQLite documentation for the ON_CONFLICT clause.
• Sometimes, you'd like to express an entity or plain
old Java object (POJO) as a cohesive whole in
your database logic, even if the object contains
several fields. In these situations, you can use
the @Embedded annotation to represent an
object that you'd like to decompose into its
subfields within a table. You can then query the
embedded fields just as you would for other
individual columns.
• The table representing a User object then
contains columns with the following
names: id, firstName, street, state, city,
and post_code.
• Note: Embedded fields can also include other
embedded fields.
Entity Create nested objects
Entity Create nested objects
If an entity has multiple embedded fields of the same type, you can keep each column
unique by setting the prefix property. Room then adds the provided value to the beginning of
each column name in the embedded object.
Accessing data using Room DAOs
• To access your app's data using the Room persistence library, you
work with data access objects, or DAOs. This set of Dao objects forms
the main component of Room, as each DAO includes methods that
offer abstract access to your app's database.
• Note: Room doesn't support database access on the main thread
unless you've called allowMainThreadQueries() on the builder
because it might lock the UI for a long period of time. Asynchronous
queries—queries that return instances of LiveData or Flowable—are
exempt from this rule because they asynchronously run the query on
a background thread when needed.
Insert
• If the @Insert method receives only 1 parameter, it can return a long, which
is the new rowId for the inserted item. If the parameter is an array or a
collection, it should return long[] or List<Long> instead.
Update
Although usually not necessary, you can have this method
return an int value instead, indicating the number of rows
updated in the database.
Delete
Although usually not necessary, you can have this
method return an int value instead, indicating the number
of rows removed from the database.
Query for information
• @Query is the main annotation used in DAO classes. It allows you to
perform read/write operations on a database. Each @Query method is
verified at compile time, so if there is a problem with the query, a
compilation error occurs instead of a runtime failure.
• Room also verifies the return value of the query such that if the name of the
field in the returned object doesn't match the corresponding column names
in the query response, Room alerts you in one of the following two ways:
 It gives a warning if only some field names match.
 It gives an error if no field names match.
Query Passing parameters into the query
Query Returning subsets of columns
Note: These POJOs can also use
the @Embedded annotation.
Query Passing a collection of arguments
Query
Observable queries
Reactive queries with RxJava Direct cursor access
Room can also return
RxJava2 Publisher and Flowable objects from the queries
you define.
Caution
Query Querying multiple tables
Query Querying multiple tables
Relation
• https://developer.android.com/reference/android/
arch/persistence/room/Relation.html
Relation
• https://developer.android.com/reference/android/
arch/persistence/room/Relation.html
In the example above, PetNameAndId is a regular Pojo but all of fields are fetched from
the entity defined in the @Relation annotation (Pet). PetNameAndId could also define its own
relations all of which would also be fetched automatically.
Relation
• https://developer.android.com/reference/android/
arch/persistence/room/Relation.html
Transaction
• https://developer.android.com/reference/android/
arch/persistence/room/Transaction.html
• When used on a Query method that has a Select statement, the generated
code for the Query will be run in a transaction. There are 2 main cases
where you may want to do that:
1. If the result of the query is fairly big, it is better to run it inside a transaction to
receive a consistent result. Otherwise, if the query result does not fit into a
single CursorWindow, the query result may be corrupted due to changes in the
database in between cursor window swaps.
2. If the result of the query is a Pojo with Relation fields, these fields are queried
separately. To receive consistent results between these queries, you probably want
to run them in a single transaction.

More Related Content

What's hot

Data Storage In Android
Data Storage In Android Data Storage In Android
Data Storage In Android
Aakash Ugale
 
C++でテスト駆動開発
C++でテスト駆動開発C++でテスト駆動開発
C++でテスト駆動開発
Akineko Shimizu
 
Manipulating Android tasks and back stack
Manipulating Android tasks and back stackManipulating Android tasks and back stack
Manipulating Android tasks and back stack
Ran Nachmany
 
Share preference
Share preferenceShare preference
Share preference
SbahatNosheen
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaSanjeev Tripathi
 
ECMA Script
ECMA ScriptECMA Script
ECMA Script
NodeXperts
 
Android Navigation Component
Android Navigation ComponentAndroid Navigation Component
Android Navigation Component
Łukasz Ciupa
 
배정섭, 쉽고 빠르게 매력적인 모션 제작하기 tip, NDC2010
배정섭, 쉽고 빠르게 매력적인 모션 제작하기 tip, NDC2010배정섭, 쉽고 빠르게 매력적인 모션 제작하기 tip, NDC2010
배정섭, 쉽고 빠르게 매력적인 모션 제작하기 tip, NDC2010devCAT Studio, NEXON
 
[C++ Korea 2nd Seminar] Ranges for The Cpp Standard Library
[C++ Korea 2nd Seminar] Ranges for The Cpp Standard Library[C++ Korea 2nd Seminar] Ranges for The Cpp Standard Library
[C++ Korea 2nd Seminar] Ranges for The Cpp Standard Library
DongMin Choi
 
Android MVVM architecture using Kotlin, Dagger2, LiveData, MediatorLiveData
Android MVVM architecture using Kotlin, Dagger2, LiveData, MediatorLiveDataAndroid MVVM architecture using Kotlin, Dagger2, LiveData, MediatorLiveData
Android MVVM architecture using Kotlin, Dagger2, LiveData, MediatorLiveData
Waheed Nazir
 
Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674
Lokesh Kakkar Mobile No. 814-614-5674
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux Introduction
Nikolaus Graf
 
Writing and using Hamcrest Matchers
Writing and using Hamcrest MatchersWriting and using Hamcrest Matchers
Writing and using Hamcrest Matchers
Shai Yallin
 
[IGC 2016] 엔씨소프트 김종원 - 모바일 테스트 자동화 시스템
[IGC 2016] 엔씨소프트 김종원 - 모바일 테스트 자동화 시스템[IGC 2016] 엔씨소프트 김종원 - 모바일 테스트 자동화 시스템
[IGC 2016] 엔씨소프트 김종원 - 모바일 테스트 자동화 시스템
강 민우
 
MongoDB + Java + Spring Data
MongoDB + Java + Spring DataMongoDB + Java + Spring Data
MongoDB + Java + Spring DataAnton Sulzhenko
 
Android Internals
Android InternalsAndroid Internals
Android Internals
Opersys inc.
 
Using the Android Native Development Kit (NDK)
Using the Android Native Development Kit (NDK)Using the Android Native Development Kit (NDK)
Using the Android Native Development Kit (NDK)
Xavier Hallade
 
React / Redux Architectures
React / Redux ArchitecturesReact / Redux Architectures
React / Redux Architectures
Vinícius Ribeiro
 
Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016
Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016
Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016
Christian Schneider
 

What's hot (20)

Data Storage In Android
Data Storage In Android Data Storage In Android
Data Storage In Android
 
C++でテスト駆動開発
C++でテスト駆動開発C++でテスト駆動開発
C++でテスト駆動開発
 
Manipulating Android tasks and back stack
Manipulating Android tasks and back stackManipulating Android tasks and back stack
Manipulating Android tasks and back stack
 
Share preference
Share preferenceShare preference
Share preference
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
 
ECMA Script
ECMA ScriptECMA Script
ECMA Script
 
Jest
JestJest
Jest
 
Android Navigation Component
Android Navigation ComponentAndroid Navigation Component
Android Navigation Component
 
배정섭, 쉽고 빠르게 매력적인 모션 제작하기 tip, NDC2010
배정섭, 쉽고 빠르게 매력적인 모션 제작하기 tip, NDC2010배정섭, 쉽고 빠르게 매력적인 모션 제작하기 tip, NDC2010
배정섭, 쉽고 빠르게 매력적인 모션 제작하기 tip, NDC2010
 
[C++ Korea 2nd Seminar] Ranges for The Cpp Standard Library
[C++ Korea 2nd Seminar] Ranges for The Cpp Standard Library[C++ Korea 2nd Seminar] Ranges for The Cpp Standard Library
[C++ Korea 2nd Seminar] Ranges for The Cpp Standard Library
 
Android MVVM architecture using Kotlin, Dagger2, LiveData, MediatorLiveData
Android MVVM architecture using Kotlin, Dagger2, LiveData, MediatorLiveDataAndroid MVVM architecture using Kotlin, Dagger2, LiveData, MediatorLiveData
Android MVVM architecture using Kotlin, Dagger2, LiveData, MediatorLiveData
 
Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux Introduction
 
Writing and using Hamcrest Matchers
Writing and using Hamcrest MatchersWriting and using Hamcrest Matchers
Writing and using Hamcrest Matchers
 
[IGC 2016] 엔씨소프트 김종원 - 모바일 테스트 자동화 시스템
[IGC 2016] 엔씨소프트 김종원 - 모바일 테스트 자동화 시스템[IGC 2016] 엔씨소프트 김종원 - 모바일 테스트 자동화 시스템
[IGC 2016] 엔씨소프트 김종원 - 모바일 테스트 자동화 시스템
 
MongoDB + Java + Spring Data
MongoDB + Java + Spring DataMongoDB + Java + Spring Data
MongoDB + Java + Spring Data
 
Android Internals
Android InternalsAndroid Internals
Android Internals
 
Using the Android Native Development Kit (NDK)
Using the Android Native Development Kit (NDK)Using the Android Native Development Kit (NDK)
Using the Android Native Development Kit (NDK)
 
React / Redux Architectures
React / Redux ArchitecturesReact / Redux Architectures
React / Redux Architectures
 
Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016
Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016
Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016
 

Similar to AAC Room

java framwork for HIBERNATE FRAMEWORK.pptx
java framwork for HIBERNATE FRAMEWORK.pptxjava framwork for HIBERNATE FRAMEWORK.pptx
java framwork for HIBERNATE FRAMEWORK.pptx
ramanujsaini2001
 
Learn advanced java programming
Learn advanced java programmingLearn advanced java programming
Learn advanced java programming
TOPS Technologies
 
Ef code first
Ef code firstEf code first
Ef code first
ZealousysDev
 
Apex code (Salesforce)
Apex code (Salesforce)Apex code (Salesforce)
Apex code (Salesforce)
Mohammed Safwat Abu Kwaik
 
Entity Frame Work Core.pptx
Entity Frame Work Core.pptxEntity Frame Work Core.pptx
Entity Frame Work Core.pptx
PrachiPatel779586
 
Shshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptx
Shshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptxShshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptx
Shshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptx
086ChintanPatel1
 
Java platform
Java platformJava platform
Java platform
Visithan
 
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
iFour Institute - Sustainable Learning
 
Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad
Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad
Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad
NicheTech Com. Solutions Pvt. Ltd.
 
VB.net
VB.netVB.net
VB.net
PallaviKadam
 
ASP.NET Session 11 12
ASP.NET Session 11 12ASP.NET Session 11 12
ASP.NET Session 11 12Sisir Ghosh
 
The Uniform Access Principle
The Uniform Access PrincipleThe Uniform Access Principle
The Uniform Access Principle
Philip Schwarz
 
ado.net
ado.netado.net
ado.net
ZAIYAUL HAQUE
 
Introduction to ADO.NET
Introduction to ADO.NETIntroduction to ADO.NET
Introduction to ADO.NET
rchakra
 
SFDC Introduction to Apex
SFDC Introduction to ApexSFDC Introduction to Apex
SFDC Introduction to Apex
Sujit Kumar
 
Oracle report from ppt
Oracle report from pptOracle report from ppt
Oracle report from ppt
kingshuk_goswami
 
Testing File
Testing FileTesting File
Testing File
malikredpot
 
Entity framework
Entity frameworkEntity framework
Entity framework
Mehdi jannati
 

Similar to AAC Room (20)

java framwork for HIBERNATE FRAMEWORK.pptx
java framwork for HIBERNATE FRAMEWORK.pptxjava framwork for HIBERNATE FRAMEWORK.pptx
java framwork for HIBERNATE FRAMEWORK.pptx
 
Learn advanced java programming
Learn advanced java programmingLearn advanced java programming
Learn advanced java programming
 
Ef code first
Ef code firstEf code first
Ef code first
 
Apex code (Salesforce)
Apex code (Salesforce)Apex code (Salesforce)
Apex code (Salesforce)
 
Entity Frame Work Core.pptx
Entity Frame Work Core.pptxEntity Frame Work Core.pptx
Entity Frame Work Core.pptx
 
Shshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptx
Shshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptxShshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptx
Shshsjsjsjs-4 - Copdjsjjsjsjsjakakakaaky.pptx
 
Java platform
Java platformJava platform
Java platform
 
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
 
Javasession6
Javasession6Javasession6
Javasession6
 
Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad
Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad
Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad
 
VB.net
VB.netVB.net
VB.net
 
ASP.NET Session 11 12
ASP.NET Session 11 12ASP.NET Session 11 12
ASP.NET Session 11 12
 
The Uniform Access Principle
The Uniform Access PrincipleThe Uniform Access Principle
The Uniform Access Principle
 
ado.net
ado.netado.net
ado.net
 
Introduction to ADO.NET
Introduction to ADO.NETIntroduction to ADO.NET
Introduction to ADO.NET
 
SFDC Introduction to Apex
SFDC Introduction to ApexSFDC Introduction to Apex
SFDC Introduction to Apex
 
Oracle report from ppt
Oracle report from pptOracle report from ppt
Oracle report from ppt
 
Testing File
Testing FileTesting File
Testing File
 
Entity framework
Entity frameworkEntity framework
Entity framework
 
Ado.net
Ado.netAdo.net
Ado.net
 

Recently uploaded

Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 

Recently uploaded (20)

Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 

AAC Room

  • 2. Saving Data Using the Room Persistence Library • Room provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite. • That way, when the device cannot access the network, the user can still browse that content while they are offline. Any user-initiated content changes are then synced to the server after the device is back online.
  • 3. 3 major components in Room Room architecture diagram
  • 4. Entity Represents a table within the database.
  • 5. Dao Contains the methods used for accessing the database.
  • 6. Database • Contains the database holder and serves as the main access point for the underlying connection to your app's persisted, relational data. The class that's annotated with @Database should satisfy the following conditions:  Be an abstract class that extends RoomDatabase.  Include the list of entities associated with the database within the annotation.  Contain an abstract method that has 0 arguments and returns the class that is annotated with @Dao. • At runtime, you can acquire an instance of Database by calling Room.databaseBuilder() or Room.inMemoryDatabaseBuilder().
  • 7. Note: You should follow the singleton design pattern when instantiating an AppDatabase object, as each RoomDatabase instance is fairly expensive, and you rarely need access to multiple instances. After creating the files above, you get an instance of the created database using the following code:
  • 8.
  • 9. Caused by: java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
  • 10. Sol1.
  • 12. Defining data using Room entities • By default, Room creates a column for each field that's defined in the entity. If an entity has fields that you don't want to persist, you can annotate them using @Ignore. You must reference the entity class through the entities array in the Database class. Note: Entities can have either an empty constructor (if the corresponding DAO class can access each persisted field) or a constructor whose parameters contain types and names that match those of the fields in the entity. Room can also use full or partial constructors, such as a constructor that receives only some of the fields.
  • 13. Entity • Each entity must define at least 1 field as a primary key. Even when there is only 1 field, you still need to annotate the field with the @PrimaryKey annotation. Also, if you want Room to assign automatic IDs to entities, you can set the @PrimaryKey's autoGenerate property. If the entity has a composite primary key, you can use the primaryKeys property of the @Entity annotation, as shown in the following code snippet: Use a primary key
  • 14. Entity Annotate indices and uniqueness
  • 15. Entity • Room doesn’t allow object references Define relationships between objects Note: SQLite handles @Insert(onConflict = REPLACE) as a set of REMOVE and REPLACE operations instead of a single UPDATE operation. This method of replacing conflicting values could affect your foreign key constraints. For more details, see the SQLite documentation for the ON_CONFLICT clause.
  • 16. • Sometimes, you'd like to express an entity or plain old Java object (POJO) as a cohesive whole in your database logic, even if the object contains several fields. In these situations, you can use the @Embedded annotation to represent an object that you'd like to decompose into its subfields within a table. You can then query the embedded fields just as you would for other individual columns. • The table representing a User object then contains columns with the following names: id, firstName, street, state, city, and post_code. • Note: Embedded fields can also include other embedded fields. Entity Create nested objects
  • 17. Entity Create nested objects If an entity has multiple embedded fields of the same type, you can keep each column unique by setting the prefix property. Room then adds the provided value to the beginning of each column name in the embedded object.
  • 18. Accessing data using Room DAOs • To access your app's data using the Room persistence library, you work with data access objects, or DAOs. This set of Dao objects forms the main component of Room, as each DAO includes methods that offer abstract access to your app's database. • Note: Room doesn't support database access on the main thread unless you've called allowMainThreadQueries() on the builder because it might lock the UI for a long period of time. Asynchronous queries—queries that return instances of LiveData or Flowable—are exempt from this rule because they asynchronously run the query on a background thread when needed.
  • 19. Insert • If the @Insert method receives only 1 parameter, it can return a long, which is the new rowId for the inserted item. If the parameter is an array or a collection, it should return long[] or List<Long> instead.
  • 20. Update Although usually not necessary, you can have this method return an int value instead, indicating the number of rows updated in the database.
  • 21. Delete Although usually not necessary, you can have this method return an int value instead, indicating the number of rows removed from the database.
  • 22. Query for information • @Query is the main annotation used in DAO classes. It allows you to perform read/write operations on a database. Each @Query method is verified at compile time, so if there is a problem with the query, a compilation error occurs instead of a runtime failure. • Room also verifies the return value of the query such that if the name of the field in the returned object doesn't match the corresponding column names in the query response, Room alerts you in one of the following two ways:  It gives a warning if only some field names match.  It gives an error if no field names match.
  • 23. Query Passing parameters into the query
  • 24. Query Returning subsets of columns Note: These POJOs can also use the @Embedded annotation.
  • 25. Query Passing a collection of arguments
  • 26. Query Observable queries Reactive queries with RxJava Direct cursor access Room can also return RxJava2 Publisher and Flowable objects from the queries you define. Caution
  • 30. Relation • https://developer.android.com/reference/android/ arch/persistence/room/Relation.html In the example above, PetNameAndId is a regular Pojo but all of fields are fetched from the entity defined in the @Relation annotation (Pet). PetNameAndId could also define its own relations all of which would also be fetched automatically.
  • 32. Transaction • https://developer.android.com/reference/android/ arch/persistence/room/Transaction.html • When used on a Query method that has a Select statement, the generated code for the Query will be run in a transaction. There are 2 main cases where you may want to do that: 1. If the result of the query is fairly big, it is better to run it inside a transaction to receive a consistent result. Otherwise, if the query result does not fit into a single CursorWindow, the query result may be corrupted due to changes in the database in between cursor window swaps. 2. If the result of the query is a Pojo with Relation fields, these fields are queried separately. To receive consistent results between these queries, you probably want to run them in a single transaction.