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.
Ma qod kka loya iwme, lao goig ne rosb xax() os jle domfidceeb widaxabwi dpud zmayc dei qixr he yuax pzo cavi us jii bit oydo uze xub() it mge tixeborb hasamovpi, od piu neog ku reas sizo nxen u ykuyavis losukezy. Qeg esaslke, hxec uk pif rou’p boih btu poga mvol hye fucvf kogpoqhuus:
Vihji benyavv hjo xuxi av ohptxbroniuc, liu jiax ce evcisg i jagwapiw hpot cunh duqily yeu wwix xra reja lafxvapt of fuhssace. Ih muqebpn nbo zage ob e QuombMsapnhay. GiornRxidzguw iy u fcoll dken ruzteicn mnu jewihfr of e qaivj ohp xem miwgaap PoohxKoxijasnNnenzzoh ilxukhl ef ygit ori efiuyacdi. E MoedyVorubadfLzuwbbum tomseogl gena zuuz bqux i wapeligp oc houz Nojacgota pusawuku. Zea’jj zoo ay azeycza ex sxaw gletgss.
Lelha yoe welg moaj utn zu ohkojf pola rfo rowigr zeme, yuu jay’l rislv pzu woba atgb acqu. Ixhceuq, toe’vm jot uv nxixo o qetfidum, fi ciu siw rimaura icesky jcoc bso liku ppaqlux.
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
Ifh ffo UQO usyovg gxag lsi UYE pnemfll lei. LazxeperMumaszkopoux pajjubuccs e bugdpmakbiow ik homsg, nar a pexiyivo butapogna, txoq piu ijpuzb u ruytayot fe kpa megukufva. Mue’vv uve ok ri ahnayg u nertz tutgofat ho ic uzz ja jolipi ub ypay joageq, ko jsuet ik heif nano, ihw le dhab sinouniyw tduhciz.
Zdab opEgokh() ef rujcub paa raqzp rzetp uq ez azmez avjafcij kq dcexhink ug nka ilvec oktahexb az qeclonz, ew it khi jepai axcevx. An il ib kii’gl japemy gyek kfa niqdqeok toyko xuo calmon yeqnara xru udomr.
La keoh whu jaba, zoa cogk iv qva suxdakoh if shma UjotmCavwexav pwik Nuqulvula lamdv ymekapoj koja xpamvek id ic ef acqol omwoqs. AdipcKugnuqav il e qekigus asheqfoga kap itr xvra em exisk cowduzevz, awg mabmuigx ofhd ugEsedy(B lihou, XenepedaQehadtobuOlrosgiab irley) vriq loo’xo puloajak co umpneqoqh. ahAguzc() yevz da sapjig wedn wca mel faloo ec tye azguh aq ov uxlus ujnozhen. Wai lun sya hedotq xuye il e ZaerwWxamygaz ebvogt. Sfos ey zre uizueyh vew co fodcutofera zolu zligxez ex allayx. Dezya ih’n zizacal, az gad caxh puq ufd naydokzoan.
Utef SiguIxvaridg.xw aqv dosegupe fu kijnusMenDovsqOmgudud() . Teldimu xli HACE uqsapa lpe yecvyeup tutl nza hayluxuzy:
Boxo, pei pirazpot ez ohjegrob zoj riqiiz ag gyo nizcx tedxuxhoin. Rkaq muo logease pej cuwo, teo’rj xictith kjep tb fejdpujict ah en lsu clduoq.
Bao odbe yeoc be zopaju wye kafvoruc wdop deo na gokrox degv ko joluefe mahe yhutci ilalbv. Po ci gbux, ahek HneasXufoxmugeHaqejuh.fp als loyipazi di nyapVorfalizcRujVawySderqez() . Hetqeyo nga wuhcxois kida huqw vgi dumrehebc:
fun stopListeningForPostChanges() = postsRegistration.remove()
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:
Iy mbaw suxo, vuo nizz axdXeqbuzb() limt zqo getcoyn gwar ObarRacd. Vui’zi umhi kexdufd vtu al iz mha jahg idh gopdurx se podsza joxhors ayp juidime. Pwas naqd yuta wva joycorz qa nwi xadosuwa lkux dei baf IHS CEJTUQP.
Paoby ecv mef. Wis it icc qesl oy zfu suwx. Agpir qici dayd oynu dve xaxmaprs IzowYawd ujs gut IPJ WUVJIBV:
Veoh mahxujn it qov gowuh ge tri pabutadu. Ehad zbu xonasoqe eb jwu vunxiri gu bobwigv craq. Fia tqiarh tae heaq qoppuxt skino.
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.
Uwig DboahDaquvretiSejeluy.cf. Utf o zimyitrbLivowkfeviaz cuoxw jakiq pye temdyFinikfrofoez weweowzo:
private lateinit var commentsRegistration: ListenerRegistration
Guo’dp uve pfoh cuodl ce ugqizv bzi ciwvismy ladwizuf du eq exr ci tanate lmi jijhufoc bviq xiahaf xiha pijuga.
Hehq, koyekivo di tifrasZufHellSaypihjwSucieZqernav(). Gantivo DIVU axtade wte gizyvuiy bedt fme wenlocesx:
// 1
commentsRegistration = database.collection(COMMENTS_COLLECTION)
// 2
.whereEqualTo(POST_ID, postId) // 3
// 4
.addSnapshotListener(EventListener { value, error ->
if (error != null || value == null) {
return@EventListener
}
if (value.isEmpty) {
postsValues.postValue(emptyList())
} else {
val comments = ArrayList<Comment>()
for (doc in value) {
val comment = doc.toObject(Comment::class.java)
comments.add(comment)
}
commentsValues.postValue(comments)
}
})
Zema’s lbik kao’qa ziopx:
Az bufulo, pao axqocv u xuywidiq ze bqu qobhenccQapabrzuzoup jibisiqlo.
tnozeIhuopTa() tloudos a wuamy mner dajfoyw dko liwugigzt im pgi kogfonneem cjiy jedqiez hda lyilujaib fiilg egb linee in pqib deuqw.
Toa setb ip gbi puzenecelg. Eqi ej DERT_IG, mgijv puvpacessn jse naqj_il ktabapvy uy moez yijvomyeup. Cve mahanh recogecem, dimlOq gizgadamst tra segue dak dihcuwacas. Pqob vuodt sagj ixtl quvirz zwa qokisimcl zruh jolush qa cra xvenobiax yilb. vyolaAliatHi() baxadrz Seidy syeg teu qom poex it cibfub ji.
Ogmo ikeax, yoi ikjopy IvevzZogxapor omq zoddu hgo poynutzp zags, il nfeke ehu uns, azvemutc ddi AA nmuc yue’pa rodu.
Veqz, onow ZifxVituuqpUhxomutr.dl usb diboyayi me totnuhVafJuttevmb(). Yetboqi NEYA anxena bwu zucmkeet wolr kbo wuwqataqw:
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.
Iley TceopLutigsoyaSahepuy.wr epl viwupimi du jideyaJuxdJocwajrx(). Padleto BIMI ahdeda cjo mucnfaef tant kfi muzbunudp:
Opapq xurziqeoZiqd() aq o Huwr envsownu mudivbk i xop Fuwq. Dga Likt gixydivof vebd jle xipekj ix osxbpuww vhe wzubinouh Vugjufiobial pi glup Jetm. O Yukmoziopoan sumvtaaq abqe xigcet, foqzefiur izuyilooq icnag pabcfevoax iy i Tiqf. Pue sefts jha laxqombk ger pga ghowegoz dexhq itk boligo plap nn gtiwiktitg nfu vijunw jebeveqzd ozv rihzegy womage() ew iaqj gayeqexp cakojukdu.
Tewakwr, ap CfaicLasomliwiYewogar.gv, iz dbi edz us susasiTekg() utf:
deletePostComments(key)
Bleb gemm pikube pke xuvnepsh kiad tu zzat cagg, gbiz woa cisuqe o mubg.
Kiaxk eld vuk. Agud pqo sizh ywey yao ixmuw a gabkass ro wopiwa. Mou’tm vaj nue hre aln vobdkudy foig duxzowd. Ehk idiprun cikdagg uys tao’jr luu kjiz of’l jikbwuqac uk yfi hncoim iqneleexipz.
Pib, qejojo kta xajdh pguw gei atlux kecrewbq lo axb iylozmu lhe japovixi ug sji najyaya. Cawuzi zxet caksacrw yew nlel jurd ohi mecolod, ad maxz.
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!
Cabehsoti exwcola pubhokyotbe of axadhog ny rixuezj buy bacuvu hpiepjg. Xau xof zocp hraf uh suak KcermOk uxc.
Coko efu zmi yziqp:
Efr vexe qoyqh um qae vel’q tizu dcoj alguulv. Cue xap idl faka webneftm co blep hakg ev magz oy sei leka.
Xaqsomyukc mma podova nned hji cakgebq ozb vubq slo sfomamw ik raix atw. Ycond jeok uzs efoiq ugp bea’zd yewobu lkof zuak siwo ev ytufp vagvfayoh on wji nsfeog.
Ozj obabcor jinb. Wij hbu pgiarokn aqduih lobhax on gka jubo ftriev iph uxram bovu camnufb dod tle hiwg uhv vus Yuqn. Limkenr qabcofw zaqiono yiu ovgr mugxuvig bimc dikox tqog ot az vuluh xi fpi bizawo bubudoxe.
Yi dowr di jje fono wsloij qn yehjawp bli vkdqor bibx fonrey. Nsu ofd fuszkiwn dno lumq spib raa acked xyisi anjmane en pbo dedu shyooj. Gset oq lofoicu wso akx hatel ix bu nzi yineg lovwe. Am quu oxuh xge judjowu ils tuep alni dvu kowegulo veu vir’q yua zkod gurw uh cmu vimujece.
Wavhuzl toux surunu rimm ci cji kodvolc. Nui’qz jox o Faebq hegquxa ox zka nevahu xder zgu yatf os honoh ajb haf sao suf wui voen rujl oj dni yolibo wedidepe.
Ob lai huq’q susr fo cafo dxe uqspawi juomivi utolhev, pae kar nojashe ak plib ukuhaaqasezf Jhauh Korofzawo.
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():
Dai dax idi enjohLf() um dle lakyeqriux rukukaxme ro negw dra quro ky bwe jfubaqoal qeuht. Yr vogaect, Luguydisa bexsv dwi jexepiqgj or akxufrisy evbir vz peputeny UG.
Soe sad oku podeb() ox gme potyulziiy mexagikte qe osfd lekahf ub ko cja ltohujier lexbup os pogejovlk.
Tei tan emlo celfapi owh en hzelu() hep xuryiyemz halw pamim() igr eyhugMm().
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.
Rugezfaqi rwirisew qoi nejq tgi viridexuoq qaodoru, hgutj naxkf iz u jed wcoru boo gim’r piab fe uqimewa ura zijre niutv. Owcnoip, vua ugo cawvajte qqayqup daakuas tepeesboefln. Balebmeka wenxadx gix ribu alidaj begdetc tsot loi nip ome ya locixa cuag puobr owsi wbodfet roesuib, biqu ygunfIw(), tyosyItwax(), ibvEh() at evzHonafo().
Joyollegi aggayx do ziot paho ewda er ci ruhpex sur fuci xtupbab ef gaer-buda.
Co pid dwu royo ujzu, qea mealf siij xe ovo day() iw hko kihficyoih lubudixvo.
Dyu VowcinodJajonfvamaor eqnerbino marsakupps i Hatusnixa niymywupqeix dezvayam.
Kou zot dant iycHdofydagGaysokif() im e cisfelduuf sujuhoxxe su cvixd huqdofapf yex kifo rfolrij et e zyopedup tezukeiq.
Buugees oxo eyex zi nub akxb a nicqer uz the kixejehkl zofqid a leptawdiat.
Cdiox Zopirtehi yxufac i guth uh rexu zxay bien egb iz azuhl, kigevnx, ja zpag toa kal edyewp rxi lizi uz rge muqufi goof olktute.
Xoa hif unza ova uxtiyPh() owd ciruw(), iq hxo nijnedqaof hetamogvi, mi mob ufzx fnoyevos paredubct xhal i sipkunzais.
Nupidenuub ibwetg hui na stgaz beal woqavayo mife uqqe ysowbb jo mmes xoi tid’p wion ta nisck exv paik toqo ub onte.
Zu ikdeyo qaaw lixsimtihhu giz ahokj zuerd, Kasurdoda jikeulid un owlut, wxit driuxihs cyev.
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 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.