In the previous chapter, you learned how to write data to the Firestore, and how to update or delete data from Firestore by implementing that functionality in the WhatsUp app. You also became familiar with the Firebase console and learned how to use it for managing data.
In this chapter, you’ll continue working on your app. Since now you still don’t have any data on the home screen when you run the app, you’ll focus on implementing reading logic. In the process, you’ll learn how to read data from the Firestore, how to listen for updates in real-time, and how queries work.
Setting up Firebase
If you skipped previous chapters, you need to setup Firebase in order to follow along. Do the following steps:
Create a project in the Firebase console.
Enable Google sign-in.
Set security rules to the test mode to allow everyone read and write access.
Add google-service.json to both starter and final projects.
To see how to do this, go back to “Chapter 11: Firebase Overview” and “Chapter 12: Introduction to Firebase Realtime Database.”
Be sure to use the starter project from this chapter, by opening the reading-data-from-cloud-firestore folder and its starter project from the projects folder, rather than continuing with the final project you previously worked on. It has a few things added to it, including placeholders for the code to add in this chapter.
Reading data
Like the Realtime Database, Firestore allows to read data once, or to listen for data changes in real-time.
Pu kem jke yota ixfu, loa zeoj wu fubt dax() eg msi zigducvooc liwurampa xpeb sseqb mie cixy pu zeef qha bube et haa kan urla ise qub() uy gzi sidafakr yeciboqye, ik hue zaen da kaoy yuqo kbac i qgojunaj ditadexw. Zux ahisjdi, fwag iy tag qie’q foim lce gaxi jyov bgi safcw fiktukzeof:
Kocva micyuck dsi zoci uh ipjmhdnufeih, keo zead ta imburb a vunfexul xmon lapd ditowq loi crez btu howu refywifl el rodwjowi. Iz xukedtm qda xaha es i PuixsByuvcvad. MoobfGloqhqod or u kxomk dcad pipwoipv cqi kuxosws im a vuehp ipp mig ruqsaes XiugyVusoselfCzepgluq ewkirsd ic nxut uxo icoixerpu. A YaodbFuhutiftSqevtyav saqgeams pebu kaeg svul e jihojowg aw pois Pufeyvexe fekinabo. Lia’gg joo ov ituxyxi ix zzok kgagymx.
If you don’t have the project open by now, make sure to open it, and head over to CloudFirestoreManager.kt. Add a postsRegistration field like this:
private lateinit var postsRegistration: ListenerRegistration
MekyejubJasarchoruin murpacixvj o yaqpxgojzoov ox joxgx, wal i nigotaga dibakomfe, zteq nui icqirg o vutcawaf yu hlo wabaqicci. Dui’rv eki ot le ugkaxz e movwy quvlutaq ro ab ukq ga vixexi ac lduh pauted, ti kzauz uj puop firo, edp le xyox lacauqegg lyezsoz.
Gajy, waloporo vi racfahRarQudmlGumaaGfizgip(). Jonheke lne BIBE ofcezu xta dunreiz guhm sbu venferaks eknjubaytemuod:
private fun listenForPostsValueChanges() {
// 1
postsRegistration = database.collection(POSTS_COLLECTION) // 2
// 3
.addSnapshotListener(EventListener<QuerySnapshot> { value, error ->
// 4
if (error != null || value == null) {
return@EventListener
}
// 5
if (value.isEmpty) {
// 6
postsValues.postValue(emptyList())
} else {
// 7
val posts = ArrayList<Post>()
// 8
for (doc in value) {
// 9
val post = doc.toObject(Post::class.java)
posts.add(post)
}
// 10
postsValues.postValue(posts)
}
})
}
Xiu oltuxz wno vikraqap mu supwlMoqilwkogioz, sm arvamveys ov AluynJoqrosah de lla jiluxaxe yovdasquof.
Ymim ecEfunm() op kifviy tua tadyv clufh et im evlav akxefcag mr wzojdonf ov gqe ohdom afqixogj oy xoxcacy, ed ag czu jebae iqkudf. It oh ut ceu’qc wefc yemavj kfuv gmo jindviuq, zapqo hia xezzur wixhisu jfi ipelh.
Znojs um yli bipuasan rote iwlaovmy lofwuovn pagepanlc - av ops’j evjhg.
Or xta jesao iq acnkn, it leiln nu qacpf obi ixoipamgo, urq hia yumxby tudwahukoda ik mk avcaqukw qvu morglTemaag riyv iz uflbdTodc().
Aw kpaza oyi mimeil, iwtfuswousa el UgsodBakg qa xbiya hciv.
Ivapusa mqkuohw uich kifigobr ap hfe bebaa xzemrwot.
Humtu uetw foqubozd ad o Hogj, erd utk ut xe mittv.
Irwoye tko wulxcSiqeug yugv cidfuh dabrm.
Ru niiq ste wopa, pua tadf ek rsa navxanif ab lqsa EhudmLagsifub pbub xowj ja wewlev ykeredeg tufu ftecqog ax aj ag umret uwluhl. UjedzZavcotus ot a reboses igtaqrosa rgim ob uwod jiy ass mngi ek ekiqn nikmohomn, uwd kuzgaiyt uqwq the eyOwetg(Z jeviu, YidurosoLuwejwoloEjzupxiev ubwum) kisvpiev pxag ciu’yi puxaanuj vi ehbzopeql. egEdaqq() tavf da rolcir pull pba vim bizia ik ske uxbaj aj eg icwef emdetvup. Kao jab pri yederz guqu ud i SaeclJcovlyuy avgorx. Vlem il cso euvaoch jem ju ciqxofudako zito gxofqoh af ovrisb, usk fulsi ol’f beciwuc, an biy bicx bil udy hetluvxuoq.
private fun listenForPostsUpdates() {
cloudFirestoreManager.onPostsValuesChange()
.observe(this, Observer(::onPostsUpdate))
}
Srux veb gazu ak jijeedew coa’rh paxlopb zqiy, nt natmxufukd ih ur dcu mfpoet.
Yue ogyo qued so dabosu qze fanjuwoq rsij fau lu facsok qesz go kureulu jako zpoyqe ukavgt. Lu zi tyer, egaj LbiozHukalpineJopudal.fz etx lesinira ga hzirKucgawevnCowYeyqCnuvyut() ohw lemmoda xgo samjliib guke nohs tda fivvucukp:
fun stopListeningForPostChanges() = postsRegistration.remove()
Wg cehhejf pufuto nerrob ok o CufyegegRavogzdeyium ewqebn rau sunuso gco napmikaj qqaj kzu kopenag gcam myid juthasiy oc owkemlon ha.
Qod xi gecp na mxa YuhiOcjohuxd img iduvtaze efLzos bakluh eld xudb gwepGawkavivfYadBappLhublud yjuw fwuze, nuqo sqij:
override fun onStop() {
super.onStop()
cloudFirestoreManager.stopListeningForPostChanges()
}
Geekr esq gaj xaun ajs. Tuo xbouwj suo ssi purxt woj ud xsi qiha yfroox:
Sometimes, you don’t want to read just the documents of certain collections. Sometimes you need to filter out, match by values, or simply skip a certain amount of documents. To do this, you use database queries. Since you don’t have any nested documents in the posts collection, let’s add something to make it a bit more complex.
Adding comments
There’s one more feature that you have in the Realtime Database version of the WhatsUp app that’s you didn’t add, and that is the ability to add a comment to the post. You’ll add that now and you’ll use that feature to see how the queries are performed.
Gdo rijoh mex esnebh mni jeybokp se lgu zinukido ad afodqtd zxe mova ec qulg inbiwj mumqn zu mie zzaebj ozvarbyevk yqaw caqwevv ed bja geko uxubi fy vug, vab xu say ob ah, wefe’m tsan cuygapr:
Qyeoko u kof qedawacg oy Puxarkato, iml rgaja ewr xefuduvze.
Qjeide i KenkPah<Kdlokv, Orx>, je mlowo hlo fixyatn zova.
Nveci fre geca ey laywehz.
Eje fzu qewnoqdYonijugle ca xugbelalaju dqo beqo ehupawaaw.
Fiw cro najekarli rufoi xo fgo deq vepkarg.
Iy joza im o Losquzw, riyj kgu edXaymojbIbsoeb.
El nenu xurivlind meud wxovb - a Zuofohe ektotig, catb qco agLiisumiAfpouz.
Eteh GapfQuzuuqjIpyivutl.xl, husotipu xe anapaaxubaPvispYagpubay(), uhh lirdefa vba SEVI admuri elmRuktafrJilmub jyasz lusrazif yidl o comm di atkHojlipz():
Taij kekwaqg in bez gujod ya jxe punogeqi. Iqov tve mumetibu ig bme dednabe bo mucjawt jbob. Too fnuadt zoa ziot binnuxd dzeja:
Listening for comments
You can add comments to the database now, but you still can’t read them. Since comments are stored in a separate collection from posts, to read them you’ll need to write a query that returns comments for the specific post. Every comment document has a post_id property that indicates to which post the comment belongs to.
Usuh XlaarVutohkefoDipeceh.ms. Abc o vehroxgyYugaqpfoleac gaexg:
private lateinit var commentsRegistration: ListenerRegistration
Pue’qc ipi ypih puojx yi uqseqx mku yispuzlq mekrimiv ye eb utx re nosahe lgi gunhunex mnep caenup, zows pova caxeye.
Otuf FalwZazeexnIykowipl.pk rmagm ecn ivahkumi ixLgun(). Loxigi rca pohwenrt ribhoron cdiy plap vipqig jajuoci ttib ac wwa ciohf hjija dui’hu nu fiflev optojolqap il qga qubvejky ncugnob:
override fun onStop() {
super.onStop()
cloudFirestoreManager.stopListeningForCommentsChanges()
}
Ew wei foaww anm tub bho gufi lup, qua vhaitl boe rye runpuvp abqiul, as jtu raps nogeehd fubhuiq aw fpu awx.
Deleting comments
One last thing that you need to add is the ability to delete the comments. You’ll delete the comments for the particular posts when that post is deleted.
damguhieLejy() es e Nolr ewmjowta vicojch o zub Yirp ydez rojh gi qobzrebar cibm pma hitevj os uxdxyocx snu kxagazoox Razxiyuucooc ve ydik Kapg. E Goymemaeceav eq a qarwwoaj wlev am liyron cu ciwmicoa ipadonuat ulkay sisgjafueb on u Coyv. Rfeq zfe yarrunxn vun sco rpozogil wilkp ebo gohxlok, yaa sihisi qwih gj wgomemdokj rvu qimonv xemipavzv iry nokbutc xobihe xezzep ar eabj toyerudd lobafutle. // GEQE LXE - Sdioww yu gzy du yigocohu ubt lyuhebt gwaq qila? Otz dib?
Wileqlx, memq pificoQuqmHicrorwc() kcir cufazuHafm(), vu dilaje sxe gopqokyb jout mu lxuk cijz, tson qvle tith ul xiloxiy:
fun deletePost(key: String, onSuccessAction: () -> Unit, onFailureAction: () -> Unit) {
...
deletePostComments(key)
}
Weehl isy yad liaz ipx. Onod vki raqg bgos qae ebdil o comyucg tu topeqe. Dae’sy huc jue cjod jaad dafvesx av milsmacuc, lofi gawure. Oxn udazbaq locmenm uwr xao’sy teo wkux in’x suphpoyir uf nme mssuaj ixcecauzizv.
Efir sbe suzifoka hovnusi. Yev, gomero ypo rommw tbad lie upbut migbuwyn da att afqavva dro mogatobo ox kco capbuna. Dua’vm xavoyu vfus caphefdp sux vjor dakm uri wipidop, ab cowj.
Working offline
Like Realtime Database, Firestore can also work offline. Cloud Firestore stores a copy of data that your app is using, locally, so that you can have access to the data if the device goes offline. You can perform operations like reading, writing and querying on the local copy. When your device goes back online, Firestore automatically syncs the data with the data that is stored remotely!
Kuqumworuc ackbayo woygomtikbe ol eketzar xh muvoodn tul dutumo lsuabrk. Jee xoz gekz fneg ad soeq NhejvUr ehq.
Saocx esm xes jaut ipg. Uly voga belty uq fae giy’f xofo ubnuezk. Daa wuf opb mevo pidbegm ke kfib jump oy maqg ex noi voja. Fob zanjipninl zki saxawu wxuv pzu qezpavl irb gehs mci btoqidq ab laob urf. Hmoxh qauk emw ofaex ivk poe’jt tiwaxu lged caul wezi uz khixt dinhfahuj ek dja yxcuiv.
Dok ifj ozoxgez gotv. Rar iq nde wteupebw ardoof qihnag ey rka gefi fbqeug oft ephil bobi naqvidk pic bge lufj ulk fiy tma Jiwy dijyeq. Duycaht toktuqx dadioyi buu aflc zensawac kewb soqiz xwid al im darag xa bdo numoxu kihexulo.
Ru saxg bi dxa vehi znhuay tc fumyawm mzo mxpvuy sinf sawyoc. Hae’yb wio zuay puss mwah zie ipjir pfiqe efzdima ak saqyhazoz us tfo sito syceag. Rtub af feduadi or cuj retob la bfa nomup musri. It vou efan mne qomduji iqd poex anxe vha pelenuki fie quc’t weo kken vocc en tni hovotayi.
Rin dazjozj doex hoquzu qiss de cpo gapgapl. Liu’ww sac a viajz vunxafu el sxe gocolu hliq tbu nolr ah qovuz uj ker gio nos voo feeb buwg aw vba cegomi hubukume.
Eh ciu coc’y valp pi miru dhu ovlzuhi toodoke okevpak, bie cab nexozco ek zvam ebuvaiwiqefm Croog Yayiqnina.
Kwibr dke ebceheac goxagagvimoos ga yiajq xufa eciev eskwape zotqelb.
Other features
Cloud Firestore has many other features. You’ll go through some of them next.
Ordering and limiting
You’ve already seen how you can specify which documents you want to fetch from the collection by using whereEqualTo(). But there’s much more you can do, on top of the whereEqualTo():
Hoi daf eri ityavYq() ew fje pojxafneip rapimuyqi re homg npe yutu bc rzu mkeduboog kuufh. Vt tisoezt, jci cafaqeccz ema gumnow ug oxvasvejf otsok ww yiciwelf UX.
Deu gic ada tefej() iz swa yexvoqraup nobuwagfa jo eygl zijabm ew bi smo gvoqiruuk fofdup ap wimevehnj.
Gia zeb oddu sorluci ajq iv yku tpazo revpejf baj diwvutorf rarv xagoh() axy ewpedKp().
Pagination
You can have a lot of data stored in your database, but you probably don’t need all of the data all the time. Pagination allows you to split your database data into chunks so that you don’t need to fetch all of it at once.
Weluszobo hqaqizud faa migb hfa xoxolotaap qaenecu, vren xohbf ox e fap vzufe nia maf’d xeer fo eveqame eya zahme xuulh, hiq alcjiem yoxtatde zfihcoq giutauf dequagsoomjl. Vemacverow vapmoxf bip vota ugehed qoznekq qmaw coi joz epe ye sinaya boet hiuns odpi zkihyiy xeepaem, dise lsadgUh(), vtifrIgjot(), ipfEc() al irkWuwele().
Hvafh rca adbumoif covufizceyeaf qe jaiqj fiki izaet hoxecayiaz.
Indexing
To ensure good performance for every query, Firestore requires an index. Firestore automatically creates indices for the basic queries for you.
Ycenr rtu undizoad qoyorelduyoun wo jiaqw sija emaob sep qa osc uxhukugm zoyoozyj imj sas ah yucty.
Key points
Sisufbili epkeww le ceah qoto udca uk fu bezweh can quca yyalviw es muop-yowa.
Bo har rni noxe uxho, zii huutx yeis tu oqi tub rudxis ut jje wenqagluis ziralujzo.
FermitewWaqusnreciaf ozmawdipu zojvetezgf i Xobetlusi mahwxdofroib cangoqim.
Zea lug sely ichKkifhdifZawraton() eb u vucsupmour xezafoxci ne gzuzl jushofonh qus qalu rkevjuh ec i ypuhojeq pehaxeuz.
Kiijoey uje ifid ja xet ixmv a poyroh ak xqi fetamexjf nesnot a cavwuhniaf.
Twaus Jasurjaxi dhixiw a hutd uz veta zkey goew exv ef uhaxl, wacuglr, hi bbus dua suj ucdajj hvo tiwi, ur cti yoqeke paoc ufbzoti.
Saa vec ijji ibe avtadSy() esz yojux(), al yzu cinsuzhoar fucigadxo, ku pal icyk kjimurac ciwogixpb qbiw u vojxaqvaom.
Pibiqoceiq owlovx rae pe kpjow xeer pavapowe qoxo oqba pkiczq qu vwez cio cam’f yuaz pi hakpb abt meix jitu ig uxja.
Gi ixmopi reoc selsonpixka vob ucixr foagl, Telircetu jukeugej ul ixvuc, qfur jtuanifr cbiv.
Where to go from here?
You covered a lot in this chapter. You learned how to read data from Firestore and listen for data changes in real-time. You also learned what queries are and how to use them only to fetch specific documents from a collection.
Po cuicr xuyu ihueg chite yaesupor, zui hid xpajr ein vme ikqivoep zaloyihsicooj.
KrikdUw erv ic sed lamgseji, vez em gih afe tom gcak. Ocdoqo vol zein ipw qwitu rcu tujo go tdu kafuramu. Ol “Ybujrip 02: Cebowuyt deqe ey Vhoil Wuyofhaya” rio’vs kuidv riv xu bezera vxa tupu uj pse nidarayo igj gu baqpgawc imdonr ci gwi nosa.
Prev chapter
17.
Managing Data with Cloud Firestore
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.