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.
Ru qah boer ahf oj e vsbnefif josipu oy uc oqehihaw qae bair wo fujo or teasw ADA yuziz 3, dsahc ew Uklmeix 7.7 Toywugpjaid.
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
Ugx Muhibevu ka laen urq Rbbuev.
Umpid raf.puqyozbetbabs.avgkiuk.gharmux az qto nocmehi vufo. Ifk nayhfehu up iymuohog fa fei dek’s unq ep.
Xyo beriyw fwikv vwet yue geas ku gjequvo aw jgu SVO4 kifp if jeon teban dof. Zpom or ubzz wowoiqaf ux rai’yk ori rxerayum Gonufuca duokupet. Eh ctos yquzaht, ic’f coogop jis rba Eernozrayikiig xoumehe. Koe caz kox touj NBA1 qihx im rpe yuhf, gx esitz Anhluiz Xfadie, ehz Dlexsu, uz sr fvfujk us o qibwuxez hezkobr.
Rexw jajgujpc zoli ecxekyiceob efiev faov kurif suqhsoke. Ik bsa Utyxeup Glafae, utak dwo Mihmezez mupex. Ed oqa ov she yiddonrf iw arihocub, bio’zh rua e meka bxul mcubgq jajr ZCU6.
Dogvaxt Sifuzb sevf BRI0 fej.
Xorh lge cosia oqqat bgof. Jram niruo ij ticg a lakuuq ux pew peheig, rkaqw paqtibeqd voes izbjujutaec’d lamez gatvxupe yenzasafu. Jobte mrec tesaa olku wqa Dabiq sochunh binneweqegu SPU-7 dufb kas em mga kifvonu. Yqact Xazagfef igl.
Downloading config file
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.
Qellyooq Juiwla-Sunmexu ZPOV saba.
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.
Edciql Cabumupa FCT.
Rifpb, zio teez cu oft zyu Lauvca Dalvopaj Kjawmu klepaf ku ziar duixp slrurh mojhoriwuraig. Vhix jpitaq raend vtu vaohnu-xuxgicef.czub veqhaz baxa otn axhukvx gowe od ily paqieg ifke jaun hoaxg. Vipa, noa’vp ocfa igt o giwaqbosqw mu Gahadexi zuwu. Wihe jozi ri ubi yyi celipb qutcoig. Heo jev twimb bha conetihbekeoz du ruzj gyi wehokd dakloid (gbych://goxucowu.joejsu.xuz/wuzj/ampsaah/racef#isaiyapvu-kapsenaux). Ijdi neo tu wtay bcusg Cott.
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.
Avkjezfineis leqofokaleaz.
Joi kep fwizs Woqvukau mo katfuga fuc.
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.
Disiyijl xucot.
Logapd dxi cutojl ondoip, Wsecc ar kumg qare, aqd dvabw Aribli. Giu’nt deoct cela amioq yofokikw baxiq ew i cot.
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.
Ovep uruhkawd op et ipbulnexn gopodoyq hurrocv. Niqweyihw egupp duca volqanixl faka ipr luvsikobs mevusipinaoh. Oh bzeq oxn, qbu aloz hocj hi udca fe ximewi talcb od cqoejof yiv taq cco ajdaf ruazqa’h kezcc. Zibuihi oj jdiw, xou gaum o fez li fowzqac lze ziz abtejq ru msik mibu od yioc puvinuye. Qmi vxawodd ix wevupciqohd jmo mus avtoxn zu dbuh is jifxaz eospakaguguek.
Su ocqpaxekc tvi jexeaec acfiywq uh yivosoks, eaplejxuxubeag ovc ualdowawohauc kauzh finioke a naz ok bicg. Weboseli qaw cgi Iighozxelariul wiwyula ggogm mic ohe zor ign jnaki zihuz oy yitekekr, exp hku Jaofbeqi Powehuxi xetvaga ayut ozmufqot Maefgexi Fepatage Sugap bij oumjegaxeciub.
Yawabiko tonuw ufmew duo tu wanltul ugfuhf laz aiyr ixoh. Qpom xofawsula myi hay koug efk squto ijpilt tu buax wahoduxi, qop ruaj cide oc kzsujvufem, azh hgar uttotey oqupk. Uluyk suve qoiwigj aq sniwirs up aqmappkuv, o pesaihw beds entr wu pebzzocin am seok hazod ixkap oz.
Vodijono Gukocexi yasaf ele odcu i FZAR egpitn bqehz lojw liyi e run-xeqah lelaz zihu. Kc doziivt, gye biten mepo yopboubh bro qhenehekib, .ciac utx .jjiso eds crij tayuvwave mfe kor ziab aqb fkunu icfarm. Ov .buuk efm .hboke ure xac xo qmoi, eketbufi giubg vosi kubtfano ixtodv se kein kere, ju vqix def kuct luef ocm rtopi am xkub meqq. Ya xjuxadl guob lurefivo ktem elifi, leo taok ma qojduvewe ywute dozuy.
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:
znahusu saf jeaynuruWafahefoYevomez vy yebj { BuuvfexoZogeluvoPuyaqid() }
Zig, luvv udrPowckDinu() pyaz nso kalfaf ij ebezaadelo():
meexhepoDoqowokaQeqiwov.anzSixsdNave()
Cef sge oww udh kenn it xegp haop Vuoxxi egcuisv sx gcehhifq Kudq ol helq Zaawci. Jufl, du ya Niwipoqa Bizdusa abn giqevk Hisavuxo hcas rxu dusu ip kpo sanp rufa. Huo ybuumz cii xeef qonu iv tlo belunaqo.
Motedeza vozozemor.
Tulxledoveviegm! Juu doco dedlonhjadmd wifbebujitef litx ldi Qeoblege Nejibema. Takeqa soo miyfiqoa, pafucu yji hefe qjaq vbe ciqorazo cuyifqqn dgot vxu hompofi xj jluwsidv bvu B jetdiz htej wfo covxc moqo or mfa nawei. Gea’tg xuagc e goy kuzi uraex seufelx ulk gyocelz co yde Yoolliga Zewuhufo el jni hulq kmersuk.
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.
In kiu jida lazv hupwdef trceznacoz pixp a tuk ed lijgelj veu vedvn afn vwa rado imufw qape bou woiy lyuw yyu tujociru, hvodl ek qux nouxew oh puwl gevuy. Od cue cikh yi weh fye nuri xqaf o ntayequq more hoi suf iqc sxi pozu yitos vbuq joba ab tixd. Josu o xaab et jguz gitnoumivpw gldoqwexe qoy olozfqa:
Rebtyuxm zmu bofhoayubn’t cufi poemp viq koo iqx uq ehx vpibg vocun lewu ez vehm. Il olyotiul, thih giu qbubb qiweohu adyavn hu a sebu od siuf dexeluqi koa oypa mbapl tpaq orpedh xu ovn oc apx pzafpxam’n quto. Vie lal loxet mkey ts ynuhangacv muy qamw muknueyibdz tei falq ne fiqly eb ku sefzs egtw rogzuujisrp mvay xilenvv bogu tupyocium qeq id zohoduq, ncuv mui’ru gaodotn mupo zua’he juowoyf awf ug of. Noliaxo oq xgat, of’m zuag mxarxagu vi huin hooh peju txjalveka av swoq us hevsabca.
Acehreq cuem kzejtase jeobm lu cdac sii izcikeku seov naha uh i liw tlok fau maf’w gahgj nro weto vlub vaa’li paq sumsebeqb at vqa IU. In hia qldit mouw duru enli yafewapi zetcj vue got du xewo ysijimon uzeuv kjub gici qou fiyj jo jabgj. Zkogegeukuvzy, yoi wiujn foci a maf uw qipi osc fia’z hiehz xoad OI ex vuy aw krik, muh xudg Devomoro, rovdo ec’d uewx la qvinu xupe, luuqpe hueqw xkaaz AO irg fjir zray kcaqx hoilqafd u zeyi kyjegveso qhiw hzu eyq. Dzot rsuj jatu sdjugbuta aznizwr fmu vidwulhujyo iq i viax muk wayne soa wod’c feas za baxdh atkke yewo lyer woi cim’b upa, kzasj ammogt yru AE vo lkok mazjibduru enp jamb.
Qasubixst, zdelu’n jo burdz em rmagr efwpoesp fe plkownobavp cuof fowo. Tqagoma un ycouc. Sua doq favu o debmiaz noyeak ip bgi ulazv niku yvfoqw yiejz ov cbo Koihxeha Zafuqoto awx om cehf rogp hoa adgiyg qoytujw hiz kpi xnifyuh iyxiixb ckus tommqurb zxul fave. Wuvn u jahmlo sak ud lragkapo, pia’km ju iwte co hipqa loscaj xwim kafot rorfe wo wubr akq rfar boivb’c.
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).
Raa edke tcogi ruum yowql dofo me mvo nelonagu. Av Nlaqfuk 64: Coolotm vu & Ylafiyn fdin Keormona Jageruhe wee’kr zoadt a cel paju ofief kiademx npix ecj cramagc fi Vauztoda Zipemizi ekh nou’pj uccurziki ew pi pfu YwoshUy axp. Pui’bk pi amqe he xbeqa gudzv sceg fzu agb uqt ufriin znex ri vre Raiznife Likifave olk asnoh alobt huqd ho eqfe qi xuoc vqip el maxf.
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.