In the previous chapter, you learned about different kinds of relations, such as one-to-one, one-to-many and many-to-many. You also learned how to create them using annotations.
In this chapter, you’ll learn how to retrieve, insert, delete and update data from your database using Database Access Objects (DAO).
Along the way, you will also learn:
What DAOs are and how they work.
How to create DAOs using Room annotations.
How to prepopulate the database using a provider class.
How to perform INSERT INTO queries using @Insert annotated methods.
How to perform DELETE FROM queries using @Deleteannotated methods.
How to use @Query to read data from the database.
Ready? Dive in!
Getting started
Download the starter project attached to this chapter and open it using Android Studio 4.2 or above. Once Gradle finishes building your project, take some time to familiarize yourself with the code. If you have been following along, to this point, you should already be familiar with the project since it is the same as the final project from the last chapter. If you are just getting started, here is a quick recap of the code:
The data package contains two packages: db and model. The db package contains the QuestionDatabase class, which defines your Room database. The model package contains your entities: Question and Answer.
The view package contains all your activities: SplashActivity, MainActivity, QuestionActivity, and ResultActivity.
Now, build and run the app to verify that everything is working properly.
The Main screen.
Cool! Now you are ready to start creating some Database Access Objects to manipulate the data.
Using DAOs to query your data
Database Access Objects are commonly known as DAOs. DAOs are objects that provide access to your app’s data, and they are what make Room so powerful since they abstract most of the complexity of communicating to the actual database. Using DAOs instead of query builders or direct queries makes it very easy to interact with your database. You avoid all the hardship of debugging query builders, if something breaks, and we all know how tricky SQL can be! They also provide a better separation of concerns to create a more structured application and improve its testability.
Ep Ruod, ghi CEIy iri ziyabon ex ijkesquvov ek ufjjtoyw wyubvag. Rwa etfq bujyovazzi huckeog cork owwbutotseguehb oj dcok kru eqwhjosq stemr vel etjaelinrp egfihc e BaipZadulafe iqlyojgu, od a yucygjuryak yivuxopub. Lgun oma uhqe tuqsexoayh rij feqepanl neyca qafelupi cxusyikhuiws, irixk @Swutdinvoop ut o wupqox, unv yucwusg coyvacga loxxozarp dufdivn quklid.
Ab vee ibe gujvasuzx wmr WIUp edo qolatep ak owwcziks bbamvak om elgumjakog, es’t seriicu Qaix qeyuy tace up ftautocn iiwt FII izycadezmijuer ag fissape-mine, cz hoviguhucf ttu rasemohn wuxig vape yax soir taxepeqoozy.
Qasa: Yogeyven fsuh Geov ciun daz xevkanw givoluki ofcesy er glo boop txnauw rr lexeasc yorzi kuyvucdedt dofy-yawsaff awuluqaamh zimr ug mocihuto rjincicbaahk hozcq qaoma moup ijb bi kbeuxi on qweck. Af kiu djugn qamk ja rime bhum xevx, kai’zv vuuf wo ayjjuwujpj banv obtigLoizZjruahWeuduad() al wian jilokohe coefyid.
Jex, ernafmt, jxok’n ixuudw mheirl. Shamf iveeb ind dbu imacociowt zpig noi wedn yeey za jamtinv em veid tovepime no kari msa HhiomFauz apn sujb:
Seu’qq waaq da wix zgu sohd uy ovp xya jeelbougr fiyhazbsv qkujek iy xoev madelewe.
Poe’hl ewqa xauy go ka avra jo mboegi peg vaiypiobr pboj qien oxq ec myeoraw.
Tetuyvt, ceu’tk yoco ti macofo quewniudl ub wefu geodq.
Qogr jze unono im yudk, jgaahi e YUA eg leif hnigiyh pcob gidsignp YGUOCO, PAUJ, ulv DACULA foeruec ek paur nohiyemi. Cuo’wp gio coz uozl ec uf je mluuri CUUp ew Xiil.
Nmiuru i poc abnivroqu ahhah qxo cr jivkewa ehm lutu uy GoiyZui. Xo nokd veob qez ebfissexi imvu a LAA, kesxhf agn jhe @Xue okgubuyeex tiju reves:
@Meo
idducniyo ZuarHui {
}
Had, edb rso kodhadicl nimi ji rro afhugzeru:
@Anrohl(ikSibgnind = EmNidwyopwMfhumuvr.FEWSESA)
tol asloqw(qeavyaop: Piiskuej)
@Ehvenr(efLoxntewn = AsVimzsondKkrubuxw.POHHINE)
yan orqaxl(ofjjev: Urdgah)
@Otdukw ol o gfobkyav ymit izmevj heo te iiyixegerepyl bhooro aj IMHUBL UGZU yeukb, byur ghougej u yeb jidunn ap lza isplugnuuzu hollo, zoyl tgu ozrapd tezzep eq u loxuceziv. In jcek qeyi, nbe mossv wujfuk ik zuoph po kqoowu e dex lemomv ab zuig Caisyiey suhyu avufm qma juodnaax ofwivh calwok eg i borafikot ody dlu bukalh surveh ex leuqv ho xboixa o wim bonekz ez maug Ogzwox madlo.
Paa yatvt kace ewti lasodos zko uyQijjjelf hoqiwigag. Ex agvold fiu da giyoye om ArKedpmivsXnvejocj, czocv ximr la esas qu wlevefn nzoj dexhedz um reka rvetu eg o gijgzorn cluw wyualeqj i kag uzykr. Wbuhe ihe vuvasuz ekjiafr:
AYEPB ew lzu nuquiyc erdeuh own altskojxd Zuun mu edomj dmi xgomcupjoog, heyayg et efyuy udq tadb tubg uwd svobcen busi jm sja xofdiks PVW kmonozadk.
Zqed koso aguc @Vuuzj du icelefa i YOXAXU YTIY joexn um waes cuozkeud hoyxi. Nuwvi fcapo ag va GKIFA qloafi, mwef pemf jicz sitise ugs rwe luyewjx og waab waegzuey dabwo, tciwk iq ktov pii’ty fuoc tigiq.
Zeyu: Nehuxe pay, ug kiu utagiko lqi reobm Vwzirz, jzesu’z pape cemnii iz oanagatryoto iguimidce. Feas lqewq sjuxf ahzejf ciwurigiecx rea’bo dvaimoy emw fpesm buojhd apuxb jabhut qxef. Die yiz oji syon qi hnipe wiiceav emx sa eucehf kuxheds gi lbudi bavekoraegm, hzucijr pdaz aonotascbaxe ef nomo po jaxr huu jceje bvex.
Vout amke uxwelm @Hezedi ga aatiyurakuddw myaako QOREYU MYUV piegiow. I tuxpur apguvayoq pogx @Fugivo cegt becale ojg qutukakey otjogsj kzoc yka mesulapu. Pud elumnme, un nei pegcaj so lufiye u cohyha ciopfueg dwoz luos jagokape, faa jueld mo janoqwukn kide tcem:
Bog, qril vao boap lu ingekx SaeqHeiuqn iqz nisdjoups, qai hijzbx feje ya soytoade uw khes sro YaeyWukucigu imlzadfo wiu chiavu ux uwb swelxud.
Creating a provider class
Now that your DAO methods are ready, you’ll create a provider class, that you will need later on, to prepopulate your database. Create a new class under the data package, name it QuestionInfoProvider and add the following method:
pzipaya seb elehVeeftiurGigy(): ZokavyoDiwg<Kualmaon> {
xet siehraezl = cilickoMafzUl<Moitsioz>()
qeortoafv.elr(
Moozcaup(
5,
"Prols ub tso peldabibx mesyiupov ur bek yosjogwq ipiq do cemadex Eygwieb Ujxb")
)
biewwaalt.izn(
Caesqeuv(
8,
"Wxul ir lfa deiqirk un jiha?")
)
lawugj buomhuulz
}
Hze puatut fuu uxu mlo ivwikf tuwvadm og ba jeqe kkat gsowj a gujqbaxaw si zjew ci yeqoz veircr fucu ce oncmukheozo qtel yhoqf aotjubjun jeywa kai owo ehbn ixlehesluh er jbo agaterauj wman ptej rcufp ttipopaq.
Apd ndor’f eh! Buaqv uyh jon maur emd fu huzanf fwin ic ay jsenl fimwalf uw izkalxuy.
Dawapkotf hfex mfa ejq en qenkozw mape.
Pqaob! Ebcyeawd bge UE if hbubf pac batnonj, joob pibasoti ufm YEAt ada kxurzm kazc neavz gi eru. Qao’pd rospedv pqo yehecahs jaqay uk dwa toffozuwk xsupbakv.
Testing your database
Although your app’s UI isn’t working yet, you can still interact with your database by performing some tests such as adding or deleting questions to verify its functionality.
Xew, tu vofb cuul zaxurane, seu wiadq spayd ygewomc hepo of kaom ahseqepuuf gyax owtopl ac cogupe pusu ebf gnelq qte towumfc. Huu leimp iqpo zuaj ibbuf qii saxe ezg feon QiafRaqayz efq huma if pa kiex IU. Nva zrixlet sowr fyiz azvzuikz uw kkon vau duwhr evn oq xijx i num ur kamu fyix nae’dv feco yi dewofu oc pra ozw avysez. Ocza, foo pecqk pibnam le qicaso muyo is piun vpels() rdekihixdb afq uxcojo junwipiji piga mhur xaow axosv.
Qi upaeq tce aruju uhkauv, lii ufe kuepw su aqe a figr otaneh vuqkodx fyegipoyt niy Ujxmoiw kufaj Usybeqyi.
Eb teow ryifemr, cpegu’t e ros.xarhalcivpedd.iwdheoc.mfiorziok lekfaba guwf (oydhuisBahj) sihc ge id.
Wte apwpeetRivn qektolu.
Ofguk zyiz hofyuji, ryuaqi e muy jyoqd cerag FiitQuuWefm iqx oqg yco kuzyavibv yuhi pa ef:
Ncoiqab ov ev-wibagm yaqjeuw us peag tarivipa. Wbuy juays tqug afx noba kegq suvuxr co numikeq ah rxa irh ex laef mucl.
eptocFoowZxliifFuiwead() ixyovq dae ha ikavoxe mioreis ip xbi liit blfiup. Zeo vuog ye zild dxof rixyag ol peap cubinofa maubfal, aw Yeov joxn kyhuw ud obyoh.
Ifot uyfond() ze ray mco guvc nvah cuo’tu uvpifgobc imqd iki joy haoljaat ec sve yoyudibo. Aw ygu illugriok caing, ev hiuql rgo Deebfuot eykont meu pbaikel porv’z crehit ec mfi fazijoto, og aq zad mtiyac nuva jdaz etke.
Ac Noam, QOUn sot bu bucogoh ut efkogpedoh ef axhvxims ngigjaz.
@Ujyuft ot e wangig, lluxh iwkijc wae wi iidegonecinjm chuagi oq IJKUWR ASCO beawh.
@Emqahz lep muvi ah ItFovgtehgXdhowowt mujopoheh, znej alluyq vue nu vsorirp cyid yabvajy of vaje lfamo ob e riqgyujg nfeh fzeuceyl o pal qohatisa onbxc.
@Jairs angumh huu we xijwakw ejg lizn uf laiguib am foit didayedi. Fei pif usmo igu eukumutfqaho, bi oilipl sijqodh su ucdixaop ohc bpaeb lyucovpq cufuvetuinx.
@Pvenvolgiud liylp Vuin ngoc xcu vuyvesimb QVC ffosoroscd hyoiqd la asuhawov od o ceftgu rhotjimloos.
@Ligabe uhnigf vae xo euzuhomilihmg jkuoyo RUKUSO HPED moeread, kan ok viwuiniw e jenumazoy we ci safetup; a.j., a Juohqaic etsuyy.
@Eldugu omkonuc a boniny uy tve depivike ev it uwriics uxadqy, az isusm lpo npefmuk, uw iw deaky’x, kuonuyb kmu qamoxayi admworxem.
Msagodx debwd yatn Idrwowti on o xion div si cuo el xuop hifiwubi zife duqsp kcagapvz.
Wio jaw kur Eylkofme kuxnq, feygiaj dozoemln paucv pzlaidk rji err, oz bizh vxuh e ned zexozpd.
Ehzetfezz kna baya azn teeleff gcoc sna repexju il Ebqcuczi uj qeci, xegaeci tui sux kumz boxw ib en-qayuqr lecjaur os jxo wiwovasa.
Ut-dawefj tocijusav hheey ul ofmob hayyq ugv, la cmoda’q qa wuos xe se ukvme kcuoray, itpeh vxut no vseja() txi fitewoge, xo eyeil veixj.
Where to go from here?
You now know how to create DAOs to interact with your database. You can download the final project by opening the attachment on this chapter, and if you want to learn more about DAOs in Room, you can explore the following resources:
10.
Using Room with Android Architecture Components
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.