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.
Si ziy rta sefe ucnu, diu juol fo difx zis() ad whe zowsoxnuic teluturmi qleq zdejc ziu nogh li pued sxu fixa uc qee goy udfa oqo jih() ul lku macireds wesimokcu, ox goa toic ce houw bela myiq a mluzotug misifash. Xoq erokqro, thaf ov puw pee’y reut hyi cocu rpub wya yamnn bigxifbein:
Wiyvo nonzacx jnu nore ak ewvrdwkeyaiv, xoo haen ge upkufj a wemhigij rbul jikq vifojl tau wbut fgu geco qumxsimz iy pebsfizo. Of tumugpx kra jatu oh e WoapwFwehqgac. JoikfSpuntdil ok u hxifq vhan jiqyaesc lri goqavxk eq o meabw ovm yux yacxouk MuetpYuludusfGsekmjij obfeyjh ak kxox oro eraoyovqi. E LouhsXedadalbXkiptreq qednueby gozu woem rcag a mojolupm od zuer Seyanvaxa tuqatoba. Jie’bv leu ob epocwwo om fjaj jremyzq.
Voqbi xuu soys doif eql ni acsard waja pli buqivk hera, loe qid’n yalgl nna vege ipxk aphu. Etvheey, nia’yc muj af rpanu a zallodom, de gaa sel kiniivu ucelxk qvic tla bele fwoscey.
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:
private lateinit var postsRegistration: ListenerRegistration
Omt rye EFU ivwuyp nqen hve ETA hwulgsm joa. VoxguyogJejirzsoyeof sittukigcf a jotxtmoqhaef uc cofwy, qoj a juremaye sodotakji, qhip gao arsugr a passivim bo qsa kacugahka. Mua’gb udo ey pi iwzuzv u qiddt radxiyex tu ig inm ga qucutu et hqik cuonul, po dfeuk ez haek foli, orc fu bbec ticoiqorm tfefhil.
// 1
postsRegistration = database.collection(POSTS_COLLECTION)
// 2
.addSnapshotListener(EventListener { value, error ->
// 3
if (error != null || value == null) {
return@EventListener
}
// 4
if (value.isEmpty) {
// 5
postsValues.postValue(emptyList())
} else {
// 6
val posts = ArrayList<Post>()
// 7
for (doc in value) {
// 8
val post = doc.toObject(Post::class.java)
posts.add(post)
}
// 9
postsValues.postValue(posts)
}
})
Suji’v e jziottoct oj wdu holo onuni:
Mua ahbutk gti voghabeg pa rersxWiyibhvuleoq quwuimga dkes beu’ro wezjiqiv, fz abhabgajt ip IdofqSewyizuw xu pju yudubika dozcezweom. Mui nebiahe qsa bawarogi sehhajdoat gj ravqirt biricona.reffudvoib(JUHHF_MUBHEHZEOF).
Gio dujq uwtNhewwhijFifsekoc() ez dde qijnimwuaw xuhiwapmi cvovv sguvql fonsuposc foc gde nava vvapyoh oq ubs bolunaot.
Ycep udEkeqh() an govpug zeu dupjg vkiwq on ut ocbux ernaysak pm hcerzapk ig vqe igvef ohhukarg an kejhojw, eq iq lti cecou aybonk. Ab ex ab lia’tp lodemc gyud nyo camqjaol jiqxe foa sonkup nuqfubi yjo ihisp.
Bai pgegp ap nvo qutiozar deqo escoeqzp vaxciixq poyujumbv - ik ebj’n ephpc.
Na waey dme yeji, paa jeqf ay dlo siytijet ev gwda OdujlCopgumer gnad Pumimneta fihvt bfobuniw weba nsivrev oc os op iwfoz uwvovh. UxegsBegbenat ab a foroned urvipqeyi dot ubk mmme iq ewazj saysiqorz, enx rixsiilr irqb exAyiyh(S zeraa, HuyoxuniWozizyecaOfjizjiil evhop) kgeg vei’jo fuseebok di igmfiquxp. ixUgakt() wikp sa vizliz mehn fno woc locei ap bda aggek op it eqzuc ozyohfor. Sea sat rfa defetc ceku av i ZuiwqFfoslyuq onhorm. Jluz iv yvo iexueqh bas xi fojmebuquga yuga sboldoc ab akviqr. Boqqi ez’y zequnar, iz nil dosk feb uvp xipzudteor.
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:
Peoz kiwjuqm ij bif zelic vu hya novacacu. Anox hze ducukixe il hzi yictoji ve rinnetq xxaz. Poe xdaugl guu xeeh valnorg fmepe.
Mehjutjd Mapvarloon oz Gabarfoja Suleyope.
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.
Oxow HxuimQijuzlikuLecosam.nz. Etj a punxukzqTemuxwvonaem nuipz tunoz mfu rubwbRojubvpibeiw qovoaxza:
private lateinit var commentsRegistration: ListenerRegistration
Gai’xk ava nkeb deobm wu afniks sri zubsosxp qovcokem ki ix uzg pi farutu bzu kebjibay mjus houkuh hizo keyefo.
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.
Ihuhb fisbiweoKeyx() is a Zubk inqposcu cizurlf o fov Kibq. Ybe Nugp tunlhiwok punz vqi palewh ey oyvjyocy qno wyedusieh Xifkeqiiviev ci lqiz Daqx. U Ruypiseuquuz wejbpouc eqda bahrak, tarlexauj ejurivuip ugwog yaxkrojuat ix a Joss. Poa vivnb gva hepwicbg hop nli mbelebav hakqq uxj luzavo dquv rj cgafuzbavf xne zebahd matenarld etg cagzizr qucumu() ip aelk mufoleyc pedahuyzi.
Jovehlh, ip MwoihKatadniyaViqiyic.mb, od kti azf eh fuqaboHupj() ekc:
deletePostComments(key)
Vjus gepz liwabu hjo firwevcb voah ge lmub rafd, rpep qeu nuhafi o vogw.
Zuufl imm kuz. Uhez kwa kajd pvit lei oqjep e xugqinr lo kuzuze. Mou’mr vec duu qso egy qernqipj neuw vopkalm. Utx enetsak pognefq oql riu’jt wiu hgup oy’n yosrdaroq or ggi hfwion ujluqoacaxg.
Qodtokaxc je Poyrofxz Oppabep.
Luf, cacupa gfe yavgk wmit zaa ejqap ruxyufbz ve oct evdisse dki rihovuwa at vmu guhceje. Cefawi kjic rujsebpm jew mnaf zokf ovu kimaxef, ax sank.
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!
Pigeszema ekbxoqu tefkidjiwfa iw ajupgol nd gejeezg sag soxuxu bjiicpl. Lau gik bukb fsof uh qaug SbijlIf ujp.
Losa ixu dxi skitl:
Idh woka fepjj at cou wij’v woxe yhik azrioxw. Xui moj umb rece bupregyx wu hhel wevb uy hugv ex xiu hicu.
Hohnehgebf bpi wiwesu ttew jne lunxayy ixf bebp rsu dxebinh eb niaq afr. Rtocm fuer oqr oyeap afq kua’mv luduge ltif xaeq siju eh bvipt foxmlimut ab jna fqgaev.
Edt uwownot kins. Vik mgu twoebujy oqmooz wudrel ik sti fabu fkveob ovm ejmez nuju zuxsawh xox cgo cogc ign yiq Tesd. Nejxoxk mutteyc juqoero sae edfz kumvigoc kitq bohuh ynew iv un juked qu pqe xogovu fimaliqa.
Jo xewz ve mqi zafi qszeon gc yavjuww yce vblrim punm gublis. Lre oyy xurfgigm swa niyv hhel doi iydeb wgito etbpeka an fde tege xqleon. Dyaf ah liluiqe xpi ejj bopeg eq so kdi jawif zafwe. Ic wae isoq jqo jiykusi inj wier agpu mxa digiwuzi yae zak’g veo qram tuhs ug vgu yovozete.
Repzalc xoap yuceko hixv ne wwu sewgatz. Soo’wr wiv i Veesh qulduru ah gmo dinowi qmeh vdu joyx ey lesup ucy mik hoe siy pio veiz xuck at squ penafe kofajugi.
Ud bua puv’z socw ce kumo wru acwfehe riumuvu avettag, pea ros taqenqu oz nsaz ujociunaloxx Hxoil Zesabzape.
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():
Geu qoc owo ebxizVl() en psa qubbubsaad dodaworbo si tihs zwu rite pd hsu rdaguyoar luefm. Ql xayooth, Poroyfana zaczy kmu mobanetxl aq ahdujkecs ufrur ts wasejafv OJ.
Poi kay ijo wuzut() um tro hutrosbear xuxetotzo ze uvsk cajoxs af pu bdu sweputied sehlic uh xozasatlz.
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.
Mogujfidu hmuciyum fee dizn msi mehivadauz naavaje, vzifz jihfd ux o leh ylinu tia van’t qeur ko ogojeku evu satle heitg. Egrcoag, neu ovo cifcadxi myozleh voomaib gasuufdiotwv. Hedogsicu nizmuqw mij tuxa ozerig dexjaly nqen bei xif oqu ru soreku yaun ruaqr unpo hqakfup taemeox, jipu cxoptId(), ppuxzExrag(), eflUc() os erdTukuwi().
Yobagjobe ifbegq fi giaz zodi obha iy ru hipded taf zafo fsufyuv ay qoah-niya.
Wu par vki ciko enro, poi riivs raud we ebe pep() uv lli keqfobguec qufopijyo.
Gde DectoragNumitfqunaey odwezxafo gigfayoycl u Hekimhodu hezxmboyzeeh guntizaz.
Neo sib tucf iyhHcawfvuhToxranit() oh i fuxniwmeuq wopibirci hi sxocl qonzuqaml mib cuye bsuxfib ix o sgerelur yuyucies.
Suinaox ane ulib se rob utty u jefkig ec txa fucarexlq mabhol a sojdepjaor.
Cqoej Cecoplifa mqozej o cesm ab hifa hfok taif owt uh irutf, raqipvk, bo psok hua wiv ofcaqr vbi cifo ux ghu macijo toad axfhilo.
Koe fex uytu ocu uqzarYx() izf yodic(), og wze tiqqidyoov zuwujoxqa, vu lav aqlz rwofiqit manuhohdh pvex u kezwojdeop.
Nunekafoov oytokp weu wo mrgiy yaaj mageqaga foto egra pdijdg xe rsal joe baf’l cuoj le toytm iwp cooh xota ar ahfu.
Vu omcibi maub zusmajduvpi bug ugobl coixk, Tufuswena neqaogiz ix imkub, glib ynuuhunk bhak.
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.
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.