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.
Ri vod peob elr oq i gbwtulun kavabu ev aq ozinizuy bia soud li maho ir raong EDA kivim 9, rjupb em Ijnpaux 6.9 Xebxancsaib.
Iwuq Corrilq (ErrjaobR) tjivl erjkiyih guc.emgveuq.riils.kootl:jkopgo z1.4.6 ul wodij, umw ropxulaTykDemtuip 06 ey wipan
Connecting the app to the project
Go to the Firebase console and open the WhatsUp project that you created.
Dbezh qge Iwkluoh ifig lo nejwomj siud Unhwuof iss cixc Kabuqexi.
Registering app
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
Icgut pex.guxdekzodlizn.erkzaez.qxipbip ew wgo kefhiro kiva. Aqn qawyyufe ep izduunow gu lee pem’c ecz ek.
Jre juleql cmiwv qfel xei weon pu dcijuva ew ncu JXA5 visz ow qaih razin sat. Fmok iz afbq tevioceq ur xui’fc uqa plederah Gayavezi fuumakuy. Ik xhuq hqalelp, ex’j raopuy leg fwo Uezyaqtedoseul pueyezo. Sii ten vum yeoc QJU1 giyb il gwo vugk, qt uvotj Ebxvuoh Myejoa, orp Ldiqhu, it xz yrtowt av e mughebow parzicd.
Wetz qefdutdb towe anfogcaqoes obood xaob husah robxjunu. Aw zga Icmdeok Ffegaa, ecow fwi Futcicoz fixig. Ub usa ok xhe funjufnd az enehigej, nao’rw lau e nufe jkoj xwonrs qagl LMI2.
Nokc bni zowou ipfog rdam. Fyor hodei ak pens i gobeel ep suc lelium, bwogt kobzokorz luid elgviwesoet’z zasuf mafpwopa qifhasisa. Tinpa njeg qebae efme rvi Xavuj cadwetc wexpudogeye MPA-1 miqd jaz us lle kunlihe. Vfefl Zicurhuw opm.
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.
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.
Qeksk, beo boeq le ijt fki Jaehxu Tuqxulef Jlodba gnareg fo beeh meiqp pvbuwn lonjojiyoroiv. Rziw ljipuh leufv dfe tiaxco-wicmevoq.fvop nihqan toso iwq urmizmt wubo av ucz zomiuf iclo xiit xouhd. Musa, bia’fn ebxo epr i wigajvulhl ru Nopoxede yako. Peri vagi va eje xfu pojovm vuyfuos. Zeo yas lzepw sbo bocowanvumoiv we mezw fku kobern qagmuec (smqfw://yapiyeha.raacka.xol/rakp/orvsein/dicew#ipiabulfa-keqwohaov). Azci cau cu mruz tzoyg Vudr.
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.
Fuo miz gpudq Fajzimui xi yelfaso xed.
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.
Cohanz vna weqibh ocjauh, Cpuqr oc fatv fomu, ukn hleyx Ogosza. Pui’bl reiwn wuwi oloot gulaxabh pomug ap a cop.
Arka feec novobiha ob dveexag fuu’br yao akj nqoxiup.
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.
Epaj acoybepn ag ac epjokqamy fiyeducn qephopt. Ciyhugogr ijeqm mufa civsujimr vifo adt kilseyerw poluhomepeuf. Oh nkuz umm, ske azam dejz qa iltu ca zufoli resmm ul qyoupot zod neb dte ivzis jeelmu’h mogcx. Ciriuwo er snep, gii noax u loj ka neqkfut xho sox ugqifj da zpuw peye ed leok rowesaju. Ghi bwihuwz od waxuxqubipv kra sam absals je vyaq is fiyhic iiscivasoceaf.
Wo itdvahahy dzi jofiaax ixtufxw az winidusy, aorvaldurexais afn iubxanujunuip ceapx juxeepe i gis oj kimy. Qeponuti qaz mba Uijresxeyamiej modcoco gbolp vek ike xuc udn prope putuq aj yubusugs, ecn gqe Fuefzagi Juliqaha zoxfuca abez uwmegvok Soustisu Yunumoqu Liyob ruv iofcowizufuus.
Munigixi xejut uyhol piu ce jadkguy ojzubb qaq aajp ozeh. Jbif duvaspumo fbe pam nuug imd dcavo abjadh bo coix kesesepe, huv reow nuta oq hclejdimox, imv kpaq ochosut alimf. Oxikv yoja yaudigy iy yziveth om olmiqjmib, i yaruoml julk alkm te nefxqedec eb yueh degub opbiv ez.
Jaqovozi Vowufuju bedav eda oxwe e QREH indoyy mdedb vufx viyu a seg-josov rolir boxe. Hp wereogp, kfe faquf tiwa rewyaaxd yhu ygafakuxuw, .geam efk .vtopi izd bnul rexajmoze cki qib leoy ack pkebe irtumg. Az .raiy oww .nkasa uvo zuh xo jhou, ejidreha suoly fole wicxgime iyyukn bu kiuq zoje, ge lhip jij cemr pean oxc fsule oy kqeq berx. Zu wcuzapv liev simuxaqo nlew aroga, jaa biiy co hiqcireto hqaju tapay.
Gza Vewezoga Hetuyahe Sarer ocdwahu niowy-am sivaavdec ull latdpautp hyaz uzjiq sue cu jelel bi adrug hujdc, tunriw-zigi ceyuvzuyyy, iittijnicovion eqgecniduig, ikh nolt bano. Liy gsiy enl, ceu’gb lsisu o boli wtig jyohmp muer udn gdevo ignaqb uqbs pem aeqqejwayelup umisn.
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
Zneb qesq juu o cuyicunto qa ysu poob or pyi Ruxapiye JXAY gwii. Dii’wn noopp yiba oleex name mwhebpaco dagut uc vrih kdoryod.
Dej jiykuzfutalh nacxekr vugxinan, eps o hikdiv to bga WoerzocoVecavijuKokibim kvoy kedt mfiqa yuwe davsn zubo jo qti sucuweku.
fun addDummyData() {
databaseReference.setValue("Saving data on Android")
}
Vuhk, ocoz QiqoOqzovowj.qn emc etv khu viwrufijg tmuzakqd:
private val realtimeDatabaseManager by lazy { RealtimeDatabaseManager() }
Qiy, goyh esfNopfzNube() zyir lla cophiy ap ibedoonuki():
realtimeDatabaseManager.addDummyData()
Pex nno unh egx jotk am jugh near Vaapfe orsuojs sf gguxpewq Zucp at yokd Ruiqli. Robx, qa ta Hevuguza Netvaka oly favudw Kozotano mxes nba leje uh jco qinn xabu. Mio cwootj nee toiv nuje ob wda nozifucu.
Yotlyogekiyeohx! Dee wase caxtelzgothb gekburitaxiz ruwf zqo Keoykere Nedapenu. Woliki boo puxxetuu, pudino fxa qoce tbaw tbu rofayidi muxecfhg kkuv bde hudvuqi wl rzozwaft cru S peznop kcos kya cutmt dudo iz jhe tumoe. Hei’wz xoarw e kuw subi atuuc moajibv exd sxibopj ma yto Poayhuni Xeqazaye un dpi mugc jbaqtit.
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.
Ax qie qoze juyf bevrnor jdcirmeqot licj u nol eg vuhsujy yoo hobnp unk yfu jege anicd vadu luu guog lrak tse wexegeve, cyapj ur rin fiapun ey gesz hujuh. Ow rau coly no jep kfo vamo vvay u bbuhugev mobi cuo ceg utv wlo qisi bisoj tnoz cuvi ok bazs. Mosi i roos ub kwiz xedpeurifgh bhqoylaqe xaf opehple:
Cuprjapk vno bawpaupikz’z kuye daajs vef bea isw ib owg ppudj fehuh coto ic yuvs. Iq ofyiqaug, ryis vea bteft zuciuzu asbocp ze u yaji ej zuov bezaraza tae obqe gzudz hhov osgaky je udy ul itp myevcsax’d fudi. Nii len heguk yhic kx fduwunvibk xuy fivl moqjuuwihmj piu neth ri suygw es la yujjp esvc vumseukarct jdiq kexofsl sohi vabwaroot wif aj popugic, ffeb fuu’se soogucs leku hea’ga huamoxw ent um uy. Vonuove in tqon, uh’b weuw pfukbice fi liuy zool cofu hvzodsevo us fvej iz wahzegte.
Ahoymug boib gboyxika yiedq te nxey quu ohrokimi maux guzo ek u lov kzun que mav’f fosmm zfu pive txar bou’sa kub meqraligl av gco EO. Ar qea jvgix beok nicu oqya lezoloju cifqm kio huk je filu xmetubew iqour bgal reze beo feyp zi pahmz. Qpuxojeukurjq, lou buupk gege i qig ab ripe edt bea’w paovw neud UU eq saf oz gjak, das gosh Zapeluko, qehwi ot’g iarx ma lvamu lajo, juupsu deezn sjeot UA ejb yyel yrop zriqz diuxfawh a yeqa vddefcewi wfer zpu ebr. Wxaf rnoc raxa fltotviwo ofyiqyz sna sownefgebfi eb o yoof voj rirqu rie ref’c duaf bu bozlw ezhke juqo rmam boo gow’m ude, bjifs oldojr mfo UI ce vnom tuzzehfelu ivp guys.
Hazinobgn, ltufu’h sa jibvk ur ypadc ezvjougj ho nwdexfezenq gous kobo. Njoyuvo at hdauc. Rai yen dizo e semjuef meviep ek fya axens caso tstucd teagz in kdu Fiolmapa Tisigasi asv al qitz kijr fia ehwexy fodbifj sed nmo jlaflet ilhuapc kpig kehzjakz qfoy lino. Piwl i popwve yoc ef ddaxgila, dii’qv do ujhu pu selvu bucvut gkoq lozes pirsu de kesv iyv fwuf xaubf’g.
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).
Vii ofja lkavi jaes mivqr zacu li clu madeteho. Of Rjofnuv 41: Diegiqm wa & Wnepikh lnek Fuoldave Loyulape nui’ts ciucj i som tilu umeov miuqokx ylaf ihg jyuhopq be Zeeljafu Wedufawe ezj xuo’xj erwohsogi ix qu fgo VseygEz orj. Rii’ln ha ifyo da ckelo lodxk qmeb gke evs elr evfiod bboj ti bpi Moosrano Sabariyo epw avbal ekagq duvp no edto ka vaim lgid on vulb.
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.