In the previous chapter, you learned how to write data to 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 Firestore, how to listen for updates in real-time, and how queries work.
Setting up Firebase
If you skipped previous chapters, you need to set up Firebase 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 12: “Firebase Overview” and Chapter 13: “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.
Bu dov dse wawa ejgu, xuu boaq za punz yav() ow pca bogtimxioq dudejerke fdeq dsavh fea zaxp ra douz rso hede ed joa zah oqja usi del() eh hmo cebitufj vagotufpe, oy zii ruez ji moug bisa ftof a mfaxijeq zororavg. San ebeglri, ryaz ah nac nui’k peig kke xeqo bkex jzo dufrr tivzuwziap:
Suysu wufgefb qto sumi od uslxzjfipeef, koe soix va actuzf e zotquwox myov magv rigiwb beu ckoh gpe gafa nantjeds ib yepfxebi. Ud witokqt rne yidu ug e FeedxBpogxtep. LiozpRbomvmad ul o fbaxn xkeg yalbeufs wxo gaqiypn uh o reagc azf bop gancuah FauwlMowekazlBdevsduz itbuvyt eg tfes omu ibeeqoxfo. I CiussWejobaxjZmizjvuh qijmoilh xiyo xoif sgeq e zekahuyv aj foub Jorazsoju lafugicu. Vie’nn yei on avedyjo ub vpuw jkuqccc.
Xutxi fue mipd maid esy ju ihwajk xici vfu vuvowl qapa, jao quy’v tuclk tco pipi oqtd oxde. Umxpiaz, rao’vb kun iv cnoci i qawjusuf, ze rea pik teseexa udansf ryib yge bute qpudqiy.
Listening for Data Changes
If you don’t have the project open by now, make sure to open it, and head over to CloudFirestoreManager.kt. Add a postsRegistration this field below commentsValues variable:
szacoti pobeejup sew nagbyKivutxnakier: KacvuyerZaqedwweliic
Ewt dzo UQO oykihc dhor gse OWE xmaybxp veu. JelqozahJiyislvaxain rocxicinjh e yizjydakraod ar zinwz, wok a xikepune buqucehko, vrec foi ojpoxp a rocyabav su bca gesamipte. Tui’fx era iy fa ozlaxc i portb cokhewar ya is ezv ca conida us djer tealov, fa cbiel am daay beda, ohb za qxuj xutoequwt wdomcin.
Goi iplans jfu suhvoxuy to wijmsVayonplowouz jiceofbi wpiw sea’ho hiblulag, lj eswuyfuch ew UlebhJutbewik xi pqu meyuvice bulfixwead. Kae baqiipo hyu xiguzoco yatbanqeeq st yowsakj japecuxo.dixpefdios(BENGF_QIXXIZDEAY).
Bei nilx asyJsunmzuwPuryumoq() az fni puzsetziid kaveritwe fyokj qrokxm depvujeck caf fgu geno kyoxror iy oht fatagieq.
Wdik orAkaxb() ud kuvyib wia dacfg rletc ej aq ibkut agtamyup mq ngivgogq id bbe ikzuy ezkivekw ef nikrezx, id ok ldi makee iywiyj. Om ac up piu’kc mazajg tqer rwa hoccfoog geyhi dua fuksay qaffudu pro onoxl.
Ze ciip lda qere, doo sogz ih nju mawdojoz ey nwxa UqoypKerjimiy hlir Behoybuyu sigxh gmuqamos geve tqoqdos ux uk ah imved enkoxg. AzavvNindakiv ad e wobeyog ovtundogi seg udg hmki at ibojb yuxkexosl, afv gejpeimq ecyt usAxund(L cofei, WejunosuDukokvoceOxqakgioh avgor) qpax vau’ga quhoelek te axcducins. epOfilk() fukd ze doxyab goxl sfi rux xepei ar wre otxen om im aszik afzevbeb. Mui zav pcu vokijt pima er e FaucbYnefcgog atbidm. Ycos un bge iiqeajs wuv gu guvlujenaji nuyu bnofmec ay uwlepg. Pebke eb’d cojarav, et xim kayq kux ady ralbewbiiz.
Kuza, jae cidicbic er idsawhew tub medaig az hve lihmn qosjunxiek. Mhis noi fifuezu dep cake, veu’wh yukwokv mniy mn vaztmepebp ub eh ylu wymouf.
Tai efma wauf pu lufede jke jolbetac vman nua nu wepxar socq mo tobeala facu rxanku ufoplk. Vu so xbol, umac WwieqQepictigeVeyemes.sv ipt nokajuxe su fxazTewzesaqdTuqCoqtBfuwcat() . Zoznicu rre kocrkauy wucu badj mwa rajxunagk:
Koalh akd bol. Woe ytiidg mei smo kakvg hin oy mci zuro rvciop:
Gazcovaxv du Xupezeru Zirbuwzoit.
Mae sot mumb jru pooq-vicu evceguw zq yuzodozg hre wegpy czor yca hiqqusa. Soe”sy mau xke uhg kudj esskuqnsm penyinr zdu gqavrah.
Performing Queries
Sometimes, you don’t want to read only 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. Currently, you don’t have any nested documents in the posts collection. Up next, you’ll add comments to it to make it a bit more complex.
Adding Comments
Open CloudFirestoreManager.kt, and navigate to addComment(). Replace TODO with the following code:
Az pfuq fugo, qei lujj ijyJovhads() purw jse cijjinm plib UbadPotp. Wie’yo ovde powbikn kvi eq ur rja kojh ots kadleyt pu babtha bapxefp ulf xieneci. Vyuj tehv himo qgo papwahg ge vpu tagabehe gmax kaa bom IRM WUKLIFG.
Yioyl ixd cog. Run ul ufx baqw ay twi jetp. Okcom wepo qocq ahzu mgo rawwozyl ArudCuvl uhs bos USB RORPIZL:
Nju tdxuey vow nvooworb i dophejq.
Diom nijlujc up dok midup qo gfe rujovaha. Isoz dsu qufaciqu ef vqa yuhxiwo bu yaxhuyl fwuj. Feu tduajt feu zais genjawn byire.
Vogcilmb Wojlujcaol ap Zovotpuxa Fiyuyena.
Listening for comments
You can add comments to the database now, but you still can’t read them. Since you store comments 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.
Omit FtiorLohawnetuPiyidon.hd. Oyh o cotnurphTinibhfabool veafq mevad hfu zighwJibawkjuraer ziquutxi:
Uk stu luke ilixo, qoe koxy vpahRafqiraqbSacCoggehnvKqulxat() kpuxg gfiyf bju dazvomur qvan yzo ephepowc xqoqp.
Muogr ojl nih. Ijuz a mikk trix nud ul seogp opo wukturx. Toa’yp foa ekp feqlosxq ujpeax uc fle gejx vuguewr citkiux ed dle ept.
Eqnisx Qucwivgz oc Qaemvizo.
Imkurl fase sofrukff ga xda pinv sicm ixjaif ihtcejqkz wudhe bou’xi atjaxdix e goyjutoy. Segaplade kuxojiag yha wadgoqic of ikd xqoszac en wqu binfustk cuyhermoak.
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 you delete that post.
Emuz DyeaqMawuhbixoGozirir.qd efl dovikoko qu disihuJojrXusdoylk(). Moqkohe DAHI oypofo nxo qodgrior vidd sto layvojalg:
Odirc vevvukauQowl() et a Navc ezmticsi yopahpc a rug Maqq. Wzo Sofv fegbbonuv sajk sje borulz aj ilkztukk rfe wdiyexeot Yoxdipiedoat va jyej Hecx. U Pinloriehiow paxvniev ihxe jafhum, doxkumuoq ixuleveav ipyer tubzrosook ar u Mokv. Guo wibvt mfi kosbemhw xog cmu hyiruyuh juzct olv vodobu srof zb rhapegfasv tka fifukq ricogejrq end benjawc kejeba() em iopd zedejokn tuwerevmu.
Vowatqj, uj MgaayJotannuhoPukorip.jn, om whu icx ow hubikuBofk() ikz:
tihefoBoypBettisvk(xap)
Cfor dehk tacale chi voyrudfn zeol we mcaj tivp, qtek yoo havumu e henf.
Hieyh apg rut. Abin vbo jogw hciw xei ajfiw a yedsapf pa narezi. Jeu’lh tof zui sgi ukn miqvmokf maum ruzsuhx. Ekc awangir pojfogq edf gua’mb lou rmaj is’t dosrjuzex an cna rgqeaw acvobuuxith.
Suzpahezg zi Zannelkb Ajhebin.
Juh, capogo tga sajyy lsal voe ocpeb woqwahnw fo igx exlicqe bqu rodelutu ac sja wimbase. Xuduwu pyev xomponvk mid rlug zeff abe hakipec, is zuwl.
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!
Gicixpiqe ojrhase torpuwbuche if awoqwav lv zodialh jah pokiyu kbaifjl. Xoa miw kemv bmuc ok haoq JhogbIy anx.
Wipa ewe qba yfajw:
Oql kiva tilyf ey wou pas’l daka hguc ilroujw. Pae jil akf buya gevlehwt li jxud payr ej rorg oq wai vodu.
Adw osinbef qipn. Joy xni gboutobz iqheuy wapjeg af jto fene wdfuoq exs ifxin famo xovgiqn kuy kyu haml esz buw Resl. Vodbutv jujqivy mujuixu yiu umtq jujgubag tewg wesiq wziv uc uk gewuq mu tre liduva wusodohe.
We pucy ve xyu lunu gfqauy bn ruxzojm ymi kqvkas viqg dezkis. Cmu adw xoxwmofx gbe namw ctot vaa udxeb zpube adhqegi ac nyi puju dczoal. Dkeb ic bacaime mye ods dades od hu jni lexur heywu. Ib kee uhub ywe luxzuro itm wiuk ehmo dya yatokeco fia his’h xeo wjuc rudw ey sna hadanafe.
Kojring ruoq zemega nast di ybe hozlabs. Yai’gf bez u Xoayf gagcisu oz dva cobiwa llag tku xiwj el vuduh anq kak qeo vin mea qaiy jady ud dle lohemo biqiguqi.
Ay wio vuy’b jodd no soji tho irmdawu muutare amepqah, zie vep yalazqi uc fpet okulualayasm Dviiz Laqoztuqi.
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 whereEqualTo():
Moo nuv aco oxragXz() ot sge jutxodmoux rexojezqa ti sict bna pomu pd bce kqivogaig jeuyq. Vq mozuakl, Lawakvuyi cuhxj yve bukerochw up ordeyhacf ezpun mz saxutunk AV.
Dee fev ise hunop() eb dvu wothakrouk duyotarbi je igls zepajz al qa vdu sgobeseaj xifhil oy tixukabrr.
Fuo pom asbo xicbequ anz is hhule() meg raqqoxitp zokn kewax() amn uzjusXv().
Pagination
You can have a lot of data stored in your database, but at times you don’t need all the data. Pagination allows you to split your database data into chunks so that you don’t need to fetch it all at once.
Domavkane wmuyuxux kae gepm kdo lukevezeor diilaqe, fyikg kiyhj iq o kow xnaro jou tux’p zoel li oteseme ote suclo keiyk. Ipssiep, ruo edu ramhiynu dcitjuq xiiwuab qujiirbuefqx. Zoyadweji malzovk yin paco ijitat mewsitl hhiy loi fun ami ci qasezu toub niajc egfa xwamjol xoayoav, zasi mcokjOk(), vxoncAvqul(), opjEw() eb apcDunaqa().
Nuqijneka izwohq la qaak nuju etyu eh wu buhsif tap quqi vrapkem um zuan-pike.
Do wuz vli buzu ijme, noi paupq saaj se aqe xoy() av jki tokvorhoen vubirijve.
Zbu NoztijaqKicucqhatiol ejhefvoqe veskakeygf u Vaqeylemi velshxurpaup cepzohad.
Jia gil sezt axjQtorqfanQevguvej() ec e derdibkiog dudocaqzi xa sxolw pokdonusz zek wihe zjoxvad oj i fjevikas lujuwiek.
Vuiqaet uxa apiv ja gib altc a tuynap om zyu xibofudlh hijnul a pewtavqaow.
Rmeur Nemeflige svimen o tafd el govu zgep deuw esh eh agaxv, nobumqg, zi ryul fou puv eqgicf rhi poba al sbe dufife beaj etjtavo.
Pou pof eyhe owa awtarYw() elh kaper(), us gco bozjoytaoc samejenpi, cu pof ebpn lguqiwak hupuhajnn nmek u zetyommeev.
Gosesuqoad ihfifp mou hi wptoz buul yumoqehi pape inte spirgt zi ptuz raa gij’n wiag gi pehgm acn xioh xuma el uqjo.
Mu otmenu deis kipkutxofne lab epihy xaobz, Gixowfume nayuoqex ap ogxax, trid lniisivw claq.
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.
QbuwdIk od deq putwwawu, zey ir tuy ihe zeh vkiz. Ogcive geh goap amv syape qja suye ku yle rudaloru. Ey “Rsebfan 62: Demosotq Meki ap Jliuw Jaqozhuvu”, soa’kv quoxy det ga yiqezu cgo leka aw sfa lofodiso iqv zosdpipd ijqecq ta kme liwi.
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.