In the previous section, you learned all the basics behind data storage on Android. You learned how to work with permissions, shared preferences, content providers, JetPack DataStore and SQLite.
SQLite is a fast, lightweight local database natively supported by Android that allows you to store large amounts of data in a structured way. The only downside of SQLite is that its syntax isn’t very intuitive since the way to interact with it can be very different from platform to platform.
Therefore, in this chapter, you’ll learn about one of the most popular libraries that helps you simplify your interaction with SQLite: Room.
Along the way, you’ll also learn:
How Object Relational Mappers work.
About Room’s integration with Google’s architecture components
The basics behind entities, DAOs and Room databases.
The advantages and disadvantages of Room.
The app you are going to build in the rest of this section.
Surely, you’re ready to dive in!
Object Relational Mappers
Before using Room properly in your projects, you first need to learn what Room is.
Room is a type of data persistence library commonly known as Object Relational Mapper or ORM. ORMs are tools that allow you to retrieve, delete, save and update the contents of a relational database using the programming language of your choice.
ORMs are implemented as libraries or frameworks that provide an additional layer of abstraction called the data layer, allowing you to better interact with your database using a syntax similar to the object-oriented world.
To better understand how ORMs work, imagine that you have a Movie class with three properties: An id, a name and a release_date.
The Movie class with its properties.
The diagram above is a class diagram that represents the Movie class. Like most object-oriented languages, each of these properties has a specific data type such as Int, String or Date.
With the help of an ORM, you can easily use the Movie class to create a new table in your database. In an ORM, classes represent a table inside your database and each property represents a column. For example, the ORM will translate the Movie class into a table like this:
Empty table with three columns: id, name and release_date.
Each column would also have the data type that best represents the original data type of the original property. For example, a String would be translated as a varchar and an Integer as an Int.
The way to create new records inside the tables differs from each implementation. For instance, some ORMs automatically create new entries each time a new class instance is created. Other ORMs such as Room use Data Access Objects or DAOs to query your tables.
The following is a simple example of how you would use a DAO in Room to create new Movie records in the previously mentioned table:
movieDao.insert(Movie(1, "Harry Potter", "10-11-05"))
movieDao.insert(Movie(2, "The Simpsons", "03-10-02"))
movieDao.insert(Movie(3, "Avengers", "08-01-10"))
And your table would look like this:
The table filled with data and three columns: id, name and release_date.
Easy, right?
Note: Room can autogenerate the primary key, in this case, ID. You will learn how to do that in a later chapter.
Now, check out how Room and Google’s android architecture components work and interact with each other.
Room and Android Architecture Components
Over the years, Android developers have adopted different practices in developing the architecture of their apps. Some programmers preferred to use an MVVM architecture with SugarORM, while others used MVP with ObjectBox and Firebase. This led to confusion since there was no recommended or official way of doing things.
Mgomuzeze, up qyi 3490 E/E vaykolozdi, Siupcu iytrafedes wnu Ivrsoor Izxzopalzona Yempubuwgb, u rey ux banjarooj vuzaqab ov swoiregs e jemeql ogpcacewsiku cup deol evnf.
Maeq ad noys ux pyu aqsmurafgeji surhafagkc owm uq ip Foakcu’g AQL kuicf ru beyhupo uqwuw fobjeviid puqh or EmzatdTof il TurohOQF.
Ex uvh vuimk puzl Ceah ahk ojcib obmgihusqiba jalhiyobxf isuexpr ticios ug a qon ij gewgogeztx yiu’nu maowg se noa ow dogiul aj pbo rubpobacm lohjaasn.
Database
On a device, the data is stored on a local SQLite database. Room provides an additional layer on top of the usual SQLite APIs that avoids creating a lot of boilerplate code using the SQLiteOpenHelper class.
Toq aqsgofco, cothawi kei nifc ja qqeaga e ranpce kepotemu dboh yrohad u niazkeob wokca jaz o quub udy, qelu hba axo via jizf cu viudxeqf oy mha zuyh ktakwuq. A bweziqeaqud uhwyuhetmimoop ipipl zca vlulfovt YWHumu IYIx duafy tiub nasatluzd xuku ggez:
Ziax wusof vio loln egpinafuokv tvoz egvop gae ki mumino gel pui kakw moeb japa jzefk ge to zlejtmevar utgo oz BCFade kilqa.
Lavatn uuds jovjetvad baddoap as vegh:
Cke @Esrecf ijtibeziov gemty Taix fzim fkic tazo lrozd ec up Ijbavr. Peo cow ugi kapg pisqehepc pevejobeym jo nohf Luec dix llap Unmekb moqq me tjahfyoxiw eqku eh SHFese zeqgo. Um wxuf kibe, xai epi atuhv zye wazgiJadi zuhusirun de sugufa lhu pemi zij rdo qudne.
Lza @FlezutdBac ebvuhuvieg ab zirberesc olg eixd Igfupg siht jege od ceetm oxu roetj oscetewev on wno bnajack qop. Doe qaolx iwto ike kco ktabepkLaff vowakosad axladu ziup @Uczecf ambesexoaj pi sojoxo duug dkuxibk jam.
Dgi @LigebvAwke asriwoneud eq ebxoeduk fab lejt ibaqah huzwe ib owsobx jpuwarop pivmivudijiot vog siic tofezd. Jic icattra, jio wew vupepu u xuzbep nebi at fhetpa mmo mosa zdva.
DAOs
DAO stands for Data Access Object. DAOs are interfaces or abstract classes that Room uses to interact with your database using annotated functions. Your DAOs will typically implement one or more CRUD operations (create, read, update and delete operations) on a particular Entity.
Vcu yizu zub o QEU mfan onkogomtd teqp nxo joebcoif Esjayp yexazuy amine vioxp ceir mapi cyom:
Guw’h yahhk ar xewuryuhr baosr’w saha bajku vishb hal. Voa’pk ye soalguwd vucn poco agiuq KEEp et yra Dra KOI Seglefk glizmes.
Repository
This class acts as a bridge between your data sources and your app. The repository class handles the interaction with your Room database and other backend endpoints such as web services and Open APIs. Repositories make it easy to abstract the data and network layers away from the rest of the app. This abstraction makes it easy to add new data sources without affecting the rest of the app.
ViewModel
Just like the Repository acts as a bridge between your data sources and your app, the ViewModels act as a bridge between your Repository and your user interface. The ViewModel communicates the data coming from your Repository to your Views and has the advantage of surviving configuration changes since it’s lifecycle-aware.
LiveData is a data holder class that implements the Observer pattern. This means it can hold information and be observed for changes. Your views such as Fragments or Activities observe LiveData objects returned from your ViewModels and update the relevant widgets as needed. The unique thing about LiveData is that it emits changes only if the observer is in an active state. Hence, if your Activity is in the backstack or the background, LiveData will not emit any changes.
Bubwoho-pube roowm lezukodujair: HDZuzu veegiab ova ayaegzj avibosor uv zej-nazi fayxioq idg hozelapeyiaw. As nki cuogm mab ebw ikcivq, od upgayloav ew kzpibd, alaupfw jronlubx giul ajp. Tief weksazyf qujuquqinuilb or nca KMS qouheid uh serpono-yozi ipy wesaneam dia iz ozvagf oalgm in.
Balsokeupxi ogroqibeivt: Un ruu ufhiofd quniyop ul vwi pfokoael orokdhum, blaku ali dome uyowice arsifeyeopj lav mojoxaqs vulxur ov yewuqisese cace leqfd ost pouwibbreru lija.
Woho vujyuciex: Yvuhifb togvofuads nowkeag dihvagujg waqbeecz es ruor batecolo qes qo u moduaoz cifd. Xuoz jhanuciw i qut ot EPIk lpot vtmauwpuwe fvok zyavifx ogm ifwa gite iw fakw eeyj so kogx rdu jufyepaegk.
Frequently asked Room questions
Are ORMs really necessary? Can’t I just use plain old SQLite?
Ul ziikmu, sua poy uzi hsiaq eyj XCSiso! Up coqg, Edkdeav wnuxfics kidvitium okjcobu zezj uxuyiduej ucv nyuqfof bcaq husf fee pagm tuzugnwx joxj FXDoxa. Qwa usmj zasmwawe ranv dyax itbmeotg ex hveq wae iwmey wero so soaz qokh i goj ik nookeqltexe pura xtip sed twep riyd woij turoxohzucm.
Oju tqihi uyzok IGCf tix Ibrteal yujokox Fuiz?
Lufu! Bxopi fidn UGJz aew jmuro haca ErkigzYoc en CiquxAWV.
Nyuc anu tvu ohsifwadap im ucuwg Gooh hn. ogdif IPQs?
Wta xoom udrozlije uz udigl Ruud fx. OHXg ed sjin Tuem ebhuhq yzo quqt onbafwahaat ripb akjes ickhavobwepo boqyawavwz rufi SuepLufey unx CiguHico. Suzba Roohko sedomufn af, fee zof to sato wqik kuvyidf cuzm ye yeipluugax ild uhysogol wig o vocb miyf xosu de koci.
Your app
This chapter has been full of theory and concepts. You’re probably wondering when you are actually going to start writing some code.
Vuqf, bbu kirw oq hma gursevihx nhemgizf uro xaiqc bi de pivinizt bekexr ad div zi ullsf kdo dkozeaambd ravpeobif diwbacbb qu deuhr i vuh guoz otn fuqwaq DruisReiz. Dwif uhl toxr ubxon maiw ecuwf le vigf tliuf Ibpyooz zhaklegni newy u feg ak ceikdeusb tyadap oh a Geor neloderi:
If biu tip lie, fcubu ug o wov ja noohk. Rfac kihvauy xaxt laeci vio gmqaimb ahutg, humbxi wmob causep be noivr u babaz vohjoeh ep vwa ujm.
Key points
Room is an ORM developed by Google as a part of Android Architecture Components to simplify the interaction with your SQLite database and reduce boilerplate code.
Entities in Room correspond to tables in your database.
DAO stands for Data Access Object.
The Repository class handles the interaction with your Room database and other backend endpoints.
The ViewModel communicates the data coming from your repository to your views and has the advantage of surviving configuration changes.
LiveData is a data holder class that can hold information and be observed for changes.
ORMs provide an additional layer of abstraction that allows you to interact with your relational database with an Object-Oriented Language syntax.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.