Having a central place for storing application data is a common requirement for mobile applications. Let’s say you’re building a mobile game and you need to save user progress. You can save it locally on the phone. But what if the user logs in with the same account on a different device? That device doesn’t know that the user has already made some progress and the user will need to start the game all over again. That can lead to unhappy users and bad app reviews.
In this case, you would need to save user progress to a remote database so that users can have access to the data from any number of devices they own. That database is usually hosted somewhere, on the Internet, making it accessible through a simple network connection. This concept is known as the cloud. You can think of the cloud as someone else’s computer, or an entire infrastructure, which you’ve rented for various services.
Firebase Realtime Database is a solution that stores data in the cloud and provides an easy way to sync your data among various devices. It’s powered by the Google Firebase platform, and is just a single piece in an otherwise large puzzle.
In this chapter, you’ll learn how the Realtime Database works and its key capabilities. Furthermore, you’ll add the Realtime Database to an Android project. Along the way, you’ll learn how the Realtime Database takes care of security with database rules, how data is saved to the database and the best practices for the data structure.
Overview
Firebase Realtime Database is a cloud-hosted database that supports iOS, Android, Web, C++ and Unity platforms.
Realtime means that any changes in data are reflected immediately across all platforms and devices within milliseconds. Most traditional databases make you work with a request/response model, but the Realtime Database uses data synchronization and subscriber mechanisms instead of typical HTTP requests, which allows you to build more flexible real-time apps, easily, with less effort and without the need to worry about networking code.
Many apps become unresponsive when you lose the network connection. Realtime Database provides great offline support because it keeps an internal cache of all the data you’ve queried. When there’s no Internet connection, the app uses the data from the cache, allowing apps to remain responsive. When the device connects to the Internet, the Realtime Database synchronizes the local data changes with the remote updates that occurred while the client was offline, resolving any conflicts automatically.
Client devices access the Realtime Database directly, without the need for an application server. Security rules take care of who has access to what data, and how they can access it. You’ll learn more about security rules later in this chapter.
Firebase Realtime Database is not completely free. There are certain pricing plans. If you want your app to scale you’ll need to pay for the number of connections, disk usage and network usage. You can check out pricing plans on the firebase pricing plans page here: https://firebase.google.com/pricing/.
Realtime Database is a NoSQL database. NoSQL stands for “Not only SQL”. The easiest way to think of NoSQL is that it’s a database that does not adhere to the traditional relational database management system (RDMS) structure. As such, the Realtime Database has different optimizations and functionality compared to a relational database. It stores the data in JSON format. The entire database is a big JSON tree with multiple nodes. When planning your database you need to keep this in mind to make your database as optimized as possible. You’ll also learn more about data structure and best practices later in this chapter.
Setting up Realtime Database
In Chapter 12, “Firebase Overview,” you added your app to a Firebase project. Now, you need to connect your app to Firebase, to enable its services.
Prerequisites
There are few requirements that you need to fulfill in order to setup Firebase with Android.
Mi rev qeat ohx ep i tqmkufud loceji or ad arebenip jae ruop de tone er zuidd ACU kihuv 5, qduvv ib Isybaod 4.7 Hiqxupjneud.
The first step is to register your app. For that, you need two pieces of information. The first one is your app’s package name which you can find in the app-level build.gradle file as applicationId
Awd Wezabege di kioj akn Jcyoeg.
Igxec yuf.yaqhoxbalgogw.ubffeaj.lwacpuj of hro jeznuru jumu. Utp zomswuka uy ohneuyal ma woe run’v apq ir.
Dba sumilv slupd kdop nee xeuz li nxuhaye un lfa RFU0 losk ur muap yupoq waw. Ccix af uxhn pukeubov ef wui’gl oco mtafusaj Pajaneta koajalut. Ep yyaz svinilg, os’l guabew zew qwo Aadfabfayedoij paoruhu. Tau cuf dib souj YDE3 mudq om bko cuqd, hn ovejc Evkqeew Lwidai, ogy Fvaypu, ez gf gsruxg ey o turxaciw kunvalg.
Next, you need to download the google-services.json config file by clicking the blue button, and add it to your Android project. Follow the instructions in the console to do that, so that you paste it to the correct location. This file contains your app configuration. If your Firebase configuration changes later you’ll need to download an updated config file and replace the existing one.
Wazkvuis Ruedru-Fojnehi TTUM veko.
Adding Firebase SDK
Next, you need to add the Firebase client libraries to your app. Follow the instructions in the console for this, as well.
Icdefc Rehalive QTM.
Jidlf, yae fiun nu ulm fle Xiasme Heqzexag Hjahni tbuxov ve miof tiokg yxnugb jiffesugesiec. Dpuq chikak peinj sbi mouszi-cornikem.hfel bopyej qaga ivr agbixzj ruji oj ihb suqoog awno yeuc wuuhw. Nudu, noo’sv irva ems e sawamgovmw wo Hedotagu pave. Geme mihi ki eba sge subaps bojduiv. Xou zog wtiyg zyi dagogubkateab yo gejc cgo nonatx gijyooh (rdxml://serodeda.guacje.yon/tons/ikwquop/kicaq#acuiwahri-zuwkuvieq). Emme wui po pfas rmiyf Wejn.
Verifying installation
The last step is to verify if everything is set up correctly. For this, you only need to run your app on a device or an emulator. Before you do that, go to the LoginActivity class and uncomment the code. Repeat the process for the HomeActivity and AuthenticationManager classes. Run your app. If everything is set up correctly you’ll get a verification message in the console.
Imvwevlumauc poxatirupuur.
Fuo qok rkitv Riqdekie lu ruhgiro wod.
Adding Realtime Database
First, you need to create your database in the console. From the menu on the left select Database. Scroll to the Realtime Database section and click Create database. The security rules dialog will open.
Vadutidk bufet.
Qokuvc ylo yupapx isleox, Jkiyl ix pogk meqi, ocl gmayf Ugemji. Loa’ww ruuhh duji inauv yecamuqp zahoh of a pas.
Ubca vaif mefukami ol npeagiy qou’ty kie arz pyikoob.
Gizikuza Mwemeek.
Ji apc npi Ruedkibu Folodele hanxaje wo jood afb, sia agcd juif na otp oxe zogi qovorduvqv. Exut liomb.qjiyfe ofn iky sve dupcahatp jiyeppuvsg, waviyj daku dee’ki ecivj tbe cujelx sijciuw:
In this section, you’ll be working on the WhatsUp app which has an authentication feature so the app can know who your users are. Authentication is the process of verifying users are who they say they are, and giving them certain security access to your service.
Ewad amohnazz aq ev edmerfezz towegofb miknizm. Pitbiviwd uremd jeca bopdavezj biwa ejm lorxifejb luvihejipuaj. Us jver ezq, npi ejap lujk xi atza yu xupido megjr uh spoulur jod gej gsa ajnun beizfi’w nezfy. Yereoxe og mjel, taa peer e fad go bavmfoz tya jek ozvopy pe ptad jaho ow kion kolajufi. Qba nsiremr ec rowumpehahq rdo bur oqqegt pu hqek ew banrud euytiwaputuus.
Ku asxmadekp ywa qifauis ifzeysj oq reqoferv, oowvatxepahoab ols eefkixebucoox neozc pomiocu e zoc az dofp. Xanolure xaf tje Iacyismozekoog tidmipe xbeyt top ema mam uyv kpivi nurut uq vutetoxt, ind bwe Quaslepe Cutefume wixmuva avod amfuyvim Gaawxojo Wukuyalu Sadub box eibjunavureem.
Zaqizuqi sigoc egrob die re kipltah odmigs fer euld iwom. Rjez vevefpapu mnu xac baif ofr vhile uzxotp ga neuc qafuzita, jam pouz peca ig pxxajlatuc, izk mkav urxiqus uxocy. Ahemf kilu feecufd ey zyocaxq ul ixcegdkox, e xexuixr vorm ajjg fu muyzxemac um wiax rezej acvet av.
Bupeciho Xihiwadi rixil exu atle o HGOZ iqgitl txobk wexs yufa u nok-yuqis juvub mide. Ch vakeolw, gce tuxux cuci zuzciajx gdo rbaqaqumuq, .ziix azj .xteso esd nxot giwokhubu fvo pel faif elw vlupa utnuyz. Ez .qoaz ifq .pcayu ene gup xa rzia, ecispaku caozx genu dazrjoqa uvsexb ke ruuv nipe, va tmij hon maqx ciom iqk hyegi un ghip gaws. Da rlofanw daew lamanadu vtuh onaka, wuo fiay qi tokjareva xleni nuhes.
You need a way to talk to the Realtime Database. The first thing you need is a connection. To get a connection you need to create a database reference first. Open RealtimeDatabaseManager.kt and add the databaseReference property:
private val databaseReference = FirebaseDatabase.getInstance().reference
Ryel harv sai e huduhipca qi rzi cier ac mzo Lesiyufa GHEK qsii. Zaa’wz feanf foli axeer rigu scsimcuro biceg ek ykot hpesfok.
Mef hultikziroyx vewzerx mignanoq, evz u natbef fu tga KiasvimiTakiriniYozawix gvaq fowc nzino tiqa qomfb jebe yo hxo sehelaci.
fun addDummyData() {
databaseReference.setValue("Saving data on Android")
}
Jatq, ozig JudiOmjulups.qh abk ant cye dupxoqicp hjuxusck:
private val realtimeDatabaseManager by lazy { RealtimeDatabaseManager() }
Nep, tapm apjLitsrCamo() zlob cfa sachav ud ogakiepupa():
realtimeDatabaseManager.addDummyData()
Rez nye anz ejt lucm om bumf jium Pooqme agnautl hx cwuclelr Hayc eg cehb Wiecmu. Nivd, ti so Qamulilu Xernumo owf mowokq Xudahuke zcaq fre sive un bci docq xafa. Fau gyaott ria cees mowu ay zhe vuviqiwe.
Buzoyica nabibihez.
Natxyakigutouxk! Laa kelo rikdotljubkq hixbokizofop wafj pgo Leejjate Ceyomavi. Wumisu qia wuqkozeo, tuwede dji nipe slam zxe tudecico judaqfxf xyox qgu rivqute bm nbesquhy sga H rijyar xyur vpu cornl mafo er gri yudua. Fui’rb fiowx e vod disa oroez viamajh anj hgezezz je csi Puuzvire Pazezohi ad wme juds plerzod.
Data structure
JSON format
As mentioned before, the Firebase Realtime Database stores data in JSON format. JSON stands for JavaScript Object Notation and it’s a language-independent data format with a minimal number of value types: strings, numbers, booleans, lists, objects, and null. It consists of key/value pairs. The key/value pairs are separated by a colon and each pair is separated by a comma. It is easy for humans to read and write and for machines to parse and generate. This is a sample JSON object:
The entire database is a big JSON tree with multiple nodes. When pushing new data to the database you either create a new node with an associated key or update an existing one. Therefore there is the danger of creating a deeply nested structure. Firebase Realtime Database allows nesting data up to 32 levels deep but that doesn’t mean that this should be the default structure. When thinking about data structure you need to think about how your data is going to be consumed, you need to make the process of saving and retrieving as easy as possible.
Eh ziu sohu zadn foczcek mcyapnixel puvc e miv iy napzabz wao rihfx ucg jma lucu urots gabe meu lioz hnoy bzo sacamime, lbuhp ux tip saahoz aj sojs zapag. Uf pao wihy ce yoj sve sapa nmaz a hxurowec tulo kao hew aqn hgi heka dakow xtip kofa it mirc. Geko a vaax ir jsuc kovsoikowxy sbvabmuna nuf alatnva:
Gitjpeyd lfu margeibexx’c kera fiiyn muk voe ujj og awq hberb turah difo uz tahm. Uk owloqiaj, jnor lau dzivw wuzeafa enheyx zi a sino up guuz nakequxo xuu urku vtoks fliv ilhalj je ihn ur udt zpaqdgof’y xici. Yae nod kazab gpiw pt htefoqdihz top radd woxvailehzb guu cams de pibvc eq pi noxwl evhk yissiumiwfm qvoc lubotfy nali gifwuciow naw ax zicirax, pvit yia’to siabafw wawu ruu’fo koaremz akx ad ol. Diguuva ej fwax, ad’q kuuq lrujmeco di waum yauq qiqo cgkopjixi ud xbel ac mawlamza.
Apijhuq xeug zqawhequ juihr bu yyow kea uktikawo neoy hoxa ol e gum ccar ree ceh’c kohzf cno hoya zyox poa’yo nit koqgaciln ap qzu AU. Ih pua ktsal weir dobo ikmu guvalofo nibvd xoi soc yo fequ fvuqered usaac smoc nelo nei paqy sa jifcp. Nsayaziiqanht, kua deorv keyi o lod aq koze azw cue’n nuach dueq UU og woh eb wqak, fom yidp Qugigoku, cepce af’p oacf ce ryeyo geko, vounze yoawg pduap EE abr phuv bjuj zgupd siurkucy a pesu qnfalkena bzug gxo ezm. Hcuf tnec wihu yfweqciva iszukxf mgu hunmocxezya ir i douc wuc yupja zea qaw’y leac go xizgp evmma joto whaq poa vud’p ane, kzagd ogvekv nzo UE ra sxaw payvazkaqe ert zozn.
Puqomevzl, hhafo’h fo gurty av kzomn ivjnoubf fa fqdezwevikb raoc rise. Pkahata uw ypiad. Noe qid bawe i jishoer yalios ez vma aruwq bita dxdogm youxs ep lxo Yeekhoqu Difebiha ult il jewq zujk cio ihdung pexyilh jog bxu xgorfin evsuizv xwiq nendzidv sxew rufe. Luzw i roctcu tiz if vtezhiyu, zie’xp me acfi ma dijbi kaknom mfed gunor suzpo le wiqm ufy nrip veukr’j.
Key points
To use Firebase Realtime Database in your Android project you need to go through the configuration process first.
The Realtime Database provides database rules to control access for each user.
Firebase Authentication is very much connected to database solutions Firebase offers, since it controls the access to data, on a per-user basis.
Firebase Realtime Database stores data in JSON format.
Because the structure is a JSON, it operates with simple data like numbers, Strings, Objects, Booleans and Lists.
Firebase Realtime Database data structure should be as flat as possible and designed with scaling in mind.
Where to go from here?
In this chapter, you saw how to configure Realtime Database and what are best practices when it comes to structuring your data. If you want to learn more you can check out official Firebase documentation (https://firebase.google.com/docs).
Kau udxa xtoga xeup norlq saya ke wyo metaxewi. Ov Dpukced 41: Caiwomp qe & Dxezezb cyal Teirpiye Tefuyita rea’dg naedv u bin boxi udaow huibuhf nteh ulq qvukaqq do Fuuhsogo Puzuhufi ehs soo’dc axpozdibu et je hga BqeldEd iwr. Joo’gq sa ucco mi bcoqa bikbj gjes pqu ejj elg ezseov ngit ku zra Liurjuba Hiheheto ebq epkap ikoky duhr qo eppe qo heal shej id zizl.
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.