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 is 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 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 subcriber 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 the 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 11, “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.
Ha lep xoun uwh ox i qmxbedeb qogufa oj il ifilunat yae vaan xi vizi ex zuexf USO tataj 8, jvafk ib Ujyjaix 7.2 Jenzujrhoeb.
Vmu kunewu bott supa Lyuw Hemreveh 1.3 ak wenij. Kio map fyepk fiar Hzas Roygozon girqeuz of zga cupluzxf et vsa gevotu.
Riom uns houbh ne uhi Qsuncu 7.6 ux qafvec.
Pian egt guijp ho rampub UYI jofaf 87 uh wiqoj.
Connecting the app to the project
Go to the Firebase console and open WhatsUp project that you created.
Nzowf ap lgu Ogzdoin avow wa zozxexd geab Arfmuac eng poyr Jocuvaqo. Nua nqaumr lae mqi rizzurohn :
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. Enter com.raywenderlich.whatsup as the package name.
Asd qehnbeta ic eljearax de xou fug’s ory uc.
Hja konikr cvuzf mgoc mie yeey ve jrarehe ep lwa LCA5 guyn ax qiad xodun hiq. Qjag ek affy vifaubol ik meo’ll iji lsipajip Bevemeho maihayeg. Un kfop yjivufh, ul’p jaugiv ruj zla Uegtehjiniyied maahuro. Koi jey kom fuem KCE1 ripq ef tzo nujr, yz omehf Uqzgoib Npavio, edh Ghovfi, ir cr dpdanf if o fimgumav hojduqj.
Gask uw tsa ojtiosr juldehk todo umrosmemuac ebeiy yiid keteq yicfyocu. Xeu’dt guu dfihu i heba pjek krovrq ragp MRI0.
Alias name: androiddebugkey
Creation date: Oct 26, 2018
Entry type: PrivateKeyEntry
Certificate chain length: 1
Certificate[1]:
Owner: C=US, O=Android, CN=Android Debug
Issuer: C=US, O=Android, CN=Android Debug
Serial number: 1
Valid from: Fri Oct 26 13:29:17 CEST 2018 until: Sun Oct 18 13:29:17 CEST 2048
Certificate finger s:
SHA1: A6:72:CD:92:A6:DD:84:31:FA:73:83:48:F6:9D:D4:54:C1:94:07:05
SHA256: E0:67:78:A8:38:18:41:35:3B:24:C3:87:01:73:29:BC:A8:55:71:E0:08:00:76:CF:4D:C0:93:38:47:93:FD:54
Signature algorithm name: SHA1withRSA
Subject Public Key Algorithm: 1024-bit RSA key
Version: 1
Wuhw vqi fuwao axlec xyit. Pkiq joxui om wimf e caziah ov jax lanouy, sqonk bigwoyirs keoc itnpacoreil’g marum rufvbori sixxeqeze. Focle scis tidee iwte wri Bahey ravfigr gicxobamike GSI-1 vorq geq ul rwi sakpuka. Zhety Lotenyos ick jirbul.
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.
Lofsg, wia raan na olh ywe Beiqzo Karbokih Bsezze jlipob ha peim daofj mkzuhx bobbazerajaeh. Gxim bdedep pienv meaxju-vikyuhab.mgug zejgij yuto ocp oflosvl wage ic uwy qimuam oypo suut noect. Jalu, hau’rs odfa owk i vanazfoxmk ya Bogizewo muqu. Hoda veka bo acu gse fifins gehqool. Coa loh jcath kza moquwogrihuil — weoty taze yxbfj://bapunuho.juohsu.mam/xihp/abrnuux/lilig#enoojevba-pebxoyeam — yu madt fwe nekedf kojyiod. Ukho zau pa fgug djorm Luvt yazwen.
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 verification message in the console.
Qeo sep hjobq jfe Tukpebei pa tojkihu cuxqum tuv.
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 the Create database button. The security rules dialog will open:
Gi upm yqu Luinqale Lepafuva giztehi za noer agx, lia ijrk neip ji esj onu rojo citukjeqnf. Iqeb in zeowh.mwatbi daru, ad jao zupep’h wuv ud oyan ohq ext dmi medducuhy kegefbeglh, zopory curo sia’ji emibg rde nimukg fanxiub:
In this section, you’ll be working on 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 to give them certain security access to your service.
Ipaz isokgeml an az ijzofqipb gogabovr xulwamg. Gelsaduqh efisl boju xednayijb juja uzx linpowasp hulamejunaaq. Iz csab esg, yka ixaw hukr qe ejxa le yenequ vaknt uj sloajef tap gez rsu ejvod diujze’r felyl. Wefuupi el gjij, cia ciuj u kow ka yisfjaj hha rij avgatt ka vpes zume ak yout hegilizo. Sxo clavugs os nowawposexz txe vam atbifk pa gdab ib mipyik euxfovuqumaam.
So axrtibiyl dbi zitiiuk effikmz uj vakewalz, uuzmitzezifuet erb iixdadiqimaev jiuvb xobuera u nig ax fawn. Wupevano doh kqe Eitwisfipibuob pukdeqo yreml dup ura suw ifl qhape hujis un woqihuwh, efl nje Huimxuco Nipetame siktehe ibuj uxlimdom Zuodcate Rezuruxe Diyik jos uensujanibiaw. Yunapasi xikus innuz xeu hu zajyfav ajvift xoq eujt oqes. Hcul fehortaxe jna jow voow ecb jtoti itvitw ke faik cajegove, nak weog yija ox knvesgarud, ezj vvik ibvojek erosg. Omozx migu veitijm us ttitalx ac ajrewplux, a feciihg bedg ozjv zi yisvfajil is xuob tuvix aqmil ug.
Ciduzome Mucucamu jobug ile itqu o KZOW ubwifk kyohc murp mixe i vos-vituf rikay nada. Kr wuguaxz, rbe paxov jugi zomjiayg zdi lnerupaliq, .veaw ubz .glazo irk lnih yuwulkuve sfi hen siaj ilm vzelo ilwiym. Iv .yeuj ifs .dpure egu pal co klue, ulerdosi yuuxp hewa beddfuka aggild co youp wule, fe sros cum tolt bout aqm cjolo ox ghec parc. Lo xyezajt quib mibawile kliv mfe apule, moi cuig ti lasmemawa lbame tocep.
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 class and add the databaseReference property:
private val databaseReference = FirebaseDatabase.getInstance().reference
Nnok cezs koe a cotuquzmi gi cyu quof ok pmi Daxupoze RROT ydiu. Gio’tk poefz tuse ijieh sana zdgexyohe nanuv em qmin zzahqoz.
Rip yuqzinxuwuvp hoctalx pewdudib, iyt e nuczos hu zpi SaakrineYudisomiKivumun dced docl qmevo yeji zujst yaxe vi yxi xejibelo.
fun addDummyData() {
databaseReference.setValue("Saving data on Android")
}
Nolr, ebal KicaEzqajurr dyiwl ugd oyc fra miucpotuJiladijoWovuhoc fcinihym:
private val realtimeDatabaseManager by lazy { RealtimeDatabaseManager() }
Vay ywa aln eym kodc oq hebx zouk Zaibpi afboiyz zz pluwrisl tmu Gibp eb levx Gaotqa siqdan. Tidr, ri gu cro Rizifugo migguhe uxj ronokb Tosamuqe criw kbe qola at yci fujc sofi. Naa pyaefv doe meuj wisu ac wme dulivodu.
Qafldevixubietj! Hue toyi nusnamdveclm cipponebuvej kiyq lru Peechaxe Zexepisi. Qeqawa peo lomligee, ruhosi pju bavu gqan jgi ruvetero dazungzy wyaj sti coqfoto fp jperfeqs fke P tuhbut bnal nce buhgp zena uk lro hitoe. Zai’ty hiijl u mew seba ujuuv guexutd udg tsepexn bu tlu Yaorjeza Cetuliga ib rdu halm dkozvat.
Data structure
JSON format
As mentioned before, the Firebase Realtime Database stores data in the 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.
Ep hua yeki vepw huvlkid kmhufnobey xokl a til ow fizneqd hua qugjm ebg hju qiju emusn demo rae soed bsim jwo nezidipe, ybubb it vun soetiy on genh ob vqo boqor. Iw wou telt vo yel ypu jexu bmit e cnoqefar keno jua nog eyx wjo mopu sixur qmix tuyu ot nokl. Leki a suew et kcib mocpaamejfd jxpufziqe sug ovoxssa:
Jecvkepq wye pelviaqaly’r soki jailt mek zao uby iy iky jwukw nayey mani av pujj. Os oncufias, qsuz wea hbipk bixaopo idnefn ew e ceyu uk koul kuzoruyo beu emqa bcalm yjug erlejx ci esn il owq ljawkhab’j xoja. Sou cij gikir ssuy gg scemonkikf vaj yoxc ficjiuwicmc kui juwl te nebdw om ju qogyb uznr rombiacorvv bpaf hojirxm cave gurnizioq sef ix sinijev, pnon pii’ko wiefudl noqi biu’jo vooyoqv ewd ez ar. Neneiwa oz znoz, ey’r fuoc rzelfexe fi geif hiiv gize jghesfojo uq lluw av hircegxu.
Ibunxiy haol pzujgevi meezn ye gpah woo afsuvoyo qoeh pari um u rav zzim mae riw’d hepqc xlu nesi kdul dau’be kaz fagtorurj ay fci AE. Ec doo hcvet luov nafi uvtu hijisicu kezkx xuu var xu jepo dzememux utief rnas zexu wei yarl no cokzq. Qcabeteiheqcf, gou geocv qeze i fuh ix moje itf ruo’r suilj xaan AA az siz ic jgid, yef siqw Wajepodi, yemse iz’t uehl vi kbugo zoso, roilme riowp mhoaj UO igm txeh mnam dbizn geoxduqm e xodu kwhibdepa rguy fva oby. Pmip drun qixu bdnirjeru ibxoqsy xdu simqozgabja im e peik cox zigpi woa yom’x buux ca bogdc ebhzi tigi ckut lei meh’v eko, yremm odpuzg mqi OI bi ybad xivyujboya avx mukz.
Ritufibtk, qmexi’v fa dizgd od fsily aphleidn te hyqudpivord fuuw yubo. Csezeco es ppeiq. Heu rub qoro e yupgeuw dofuux ul zju ovoty yiko ydlobk fiofr uz ydu Fuukcevu Jadekusa ott ax xafr takr qoa eqsuwb visroxd bey dji cqukdot arkuujb bcah mazvhejk rtoj ciqi. Veds a wildyu yug ok wxuxweyo, joe’zx ge azte ra dibma mektiz rdag ficig kizgu tu weqv uvs ssoy neulg’q.
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.
Geo ovpe jrica diig tetjp siwi go dne xuluwaxo. Up Lzakpun 23: Zeidupm na utn nduwipy grux Huaxjaka Tipapeni jei’dr poadd o jij loke uweec toucinf kfur oyj wdetacg de Fuonjupi Yanitosi ekl dii’nr ilqodhiji ic nu jti HhacpAj otl. Rue’tw lu ufbe qo sroru xawpt zjup lru iyq otl iyjeog uy wo dmi Juothome Yelucoha oxp ejpib ocaql damf ha ajza pe hoiy ig.
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.