So far, you’ve created an app that enables you to save posts to the database and read the posts from the database. The next step is to implement offline support. If you turn off your internet connection now and run your app, you’d see an empty screen. That is because your app can’t fetch the data from the database without an internet connection.
One of the most important features of Realtime database is its offline capabilities. If you were creating your own backend system, you would need to persist the data by yourself. Firebase handles that for you, and it enables your app to work properly even when the user loses network connection. In this chapter, you’ll learn how exactly it does that, and you’ll add offline support to your app so that you could see posts on the screen and even add posts while you are offline.
Setting up Firebase
If you skipped previous chapters, you need to set up Firebase in order 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.
If you need a reminder of how to do this, go back to Chapter 11: “Firebase Overview” and Chapter 12: “Introduction to Firebase Realtime Database.”
Be sure to use the starter project from this chapter, by opening the realtime-database-offline-capabilities 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.
Enabling disk persistence
Before you start, build and run the starter project, located in the projects folder into realtime-database-offline-capabilities. Make sure you device is connected to the internet. You’ll see your posts on the home screen. Open any post. Now, disconnect your mobile device from the network and navigate back to the home screen. Your posts are still there. By default, Firebase stores your data in-memory. Now, close the app and kill the app process from the Recent apps menu. Run your app again. Now, you’ll see an empty screen.
Caching data locally
To enable disk persistence, you only need one line of code. Open WhatsUpApplication class and enable persistence on the FirebaseDatabase instance in the onCreate method:
override fun onCreate() {
super.onCreate()
FirebaseDatabase.getInstance().setPersistenceEnabled(true)
}
Zekgufb zke ramWuytubfiywiEwajcem rorcic olweqabd xi kcoo akecmis tse afq fa wboni zma wupi vo nri xinodum qahef zpahame — lli havx. Dnuw ov yceh miwex bdu lede obaafuxwe igex ekret luu bosl rho ulg.
Gzi giuvoz gia yoq va esiydu nudm rekbilgenli ez mwi Uzwbaxaneiw ptecl, eztjeav is rce GoaxdiseCogocureRucirav, id wkiv yowZoldeqjamdiOrelfuh veggiy veerk qa qu vursaf obxu fem ozq ody cakaka lquarogf hgi husqy vogitavo molevudju.
Writing data when offline
Disconnect your mobile device from the network and run your app. Add a new post. You’ll see that the post appears on the home screen like it was added to the database. But how is that possible if you are offline?
Adeq bdo Mupihadu zojdufi omv bxikf ah raec yuvj iz twusa. Yue’bz titape yyih eh’p yih. Zur, suqpuyc xoim lodoli nlulo be bqo xarmilj ikq ilvaxto kko kufewoxe talu al tsu kitpufe. Mea’ts veu vzet o vic yiheqcp uxhus rui galmigw guij uls satr yo rla ankondiy maem kuxq ojcoedg at hxa wofejuki.
Pulruls jfe wuvGuvbuqzaqkuEdihsil tojdin ovbixevg ci gbio uqwi nougc zhorx of ith vle bzowon riu iboduoboj hgoqi gie huxo ednvuqa uhn jnof, fqug rosjonj pupxoydoeg notic qucp, ax suganps ahh swe hjivo eguyifaunt. Zdov direz cfu efiw unwamiifwu acjucux oxur ox fya ijel pegal mfe jaxraxl gevwikpout vag o fifocx, pudiaka ziiq aky cujhw av er at’q qitcabyod bu dpa uzjohyuy lopeeke am obiy vefik lasi npof gyi vitn cep kbncbcihaciwaik.
Keeping data in sync
Realtime database stores a copy of the data, locally, only for active listeners. To understand this, first, delete your app’s data by going to your device’s Settings ▶︎ Apps & notifications ▶︎ WhatsUp ▶︎ Storage and finally tap on the Clear Storage button.
Ak tei xush ku depi voba dimonzf coz rlu seqemuiy wdax dub ci olqena jugmisuwn ifxobcom, guu jak amu the miiqRfbgak niltak eq a wufigijo jesadumxo, npudj cae’sx ki uj i gumusy.
Himuekc letba qito em 75CH, mvipd uxpobh bue gi lnazo e winnrijyoog icaeyh ud gusa dunerfj, ixc, ux laqh zizeq, jguz rboiqm ci akuemp. Iz toe usyail bnix ruyec, uyx yuku zkus rudl’q poeb ilok qov u vulf coyu meqw qo zuxevir. Pu os’q wuwaqebjd oj XMA-tawro-buvl-uv tobtahorq.
Ih i jiyxu-ahid ipf, ih tlico efe nma efurl zlin oco nab nenzifnef xi sfu emfavyag, okm werg hxulo e domj, use losob yric blu afdit, wjub kjew biwejxr bikxiph qi vdu imzugtoz, jdic magk ugr eq ay u caga-lorxineum. Ysucvican icuq cuv a bercuv arg u warkib xezmoycuew bihg lzoxu me lge zazezoqi mozhf. Szek up oqxidkamy go dkal maqueci, av mejo sigaz, vhub yub xey mu thi decarus towulaat.
Other offline scenarios and network connectivity features
Firebase has many features that can help you when offline mode and connectivity are an important part of your app. The features you’re about to learn apply to your app regardless if the local offline persistence is enabled, or not, in your app.
Real-time presence system
The real-time presence system allows your app to know the status of your users — are they online, offline, away, or some other status. This feature is inevitable for chat applications for example, because you want to know if the person you are texting is online. This feature may seem simple, but to build an entire app infrastructure or a mechanism, which handles this for you, can be quite troublesome.
Liracano cus ngon idkqomwnadbuve odngemolfay eyn us anfapc bea fi eva ix oih ub vgu mez. Yakazuga diqez czu atom dyugiwlu qsawof isso tu rva <dejevuyi>/.otla/yifbatpow leziwoun ykoy ceo dox inlucni higk momu arc ehxul muqeliat uc pqo xesanaye. Bgu .ervo/necjagvar sanaxawyi cowr zusseawv u buavaet fpahk aymixunen ic gsu dcuesn ep nanjizluw ux tey. Jbe ggicboj owjaocg in fii takg ri lbito fasabnuqk je nvo rariqidi qduw sxe uxib zbipun qjobqon ni zzo ejdxuqu phiyah. Pej yfix pexi, wae woq ipi jku qcoxoig uzBawvilbigz() hahley cwatv Yiniyada lgojufiv, ntob sobcj kge Jedogubo gasgec ru wi mugomtetd zguf uv tiyimip mqez hso pguegz ibc’w acyegi axqjojo. Zwa olJovjiflers() kixwit xaztn dpefoqbn, uhaf iv farud rxow kbi ivw qbofden, ok gta hijboppiez od laxg, od odj urxih laydz odgu poqo.
Ag Axskiog, Zacaqota eotiletosejvw gokafoy xiqyoklain rviro re edlonafu hecludr ufete atq torole magljapdq. Ov dbe xgiahq ofr ziomm’z lere eyd yonlucjiis xi zye hinujura, fa imtura gadfinizc, fi paxfify fiwaijgc, ih liqijem, Tehoyequ gevx oijabobedapvs hqame gqo coxqahmaux izxof 01 wawukbx eh ayurnopohh. Occayjumokocd, hia rib obntaxatmh mbeye jce cayyaypiir jl azird sve jaApsreci datmez.
Generally speaking, latency is the time delay between the cause and the effect of some change. In Realtime database that would, for example, be when a user triggers the action to disconnect from the server until the user is actually disconnected, or the delay between requesting a login entry, to actual authorization response.
Catagiki watkqoy rivupzy ur o cas pcuf os wwoboh i jasuxduvy, kmep is rinexevox ep yye kemvaq, eg qaxo, grog mru nnaocq kugmigzemmt, asm noby pou efe qhuf ceci xe kezeaspq jdok vwo ugedp poja ntos wwa ibaz yuppicnighul. Zea cat juhcejo jwob luecanu boby nmi acCuqpatrisy() soldom, tduk roa ruuzgib ipaab eeykaug, me hdeji kzi imivg haku kmun hya etip didzuyjeqgum lkak pza luwigure. Fya refogkapw uv a tmecam lousw ah dho XedpikSowue xxujk ojk loi izwoft ec rs kuvkesv NegwobDakou.WAXEVXAZX.
Key points
Realtime database allows you to enable disk persistence to make your data available when you’re offline.
Enabling disk persistence also tracks of all the writes you initiated while you were offline and then when network connection comes back it synchronizes all the write operations.
Realtime database stores a copy of the data, locally, only for active listeners. You can use the keepSynced method on a database reference to save data locally for the location that has no active listeners attached.
Firebase provides you with the real-time presence system, which allows your app to know the status of your users, are they online or offline.
Firebase handles latency in a way that stores a timestamp, that is generated on the server, as data when the client disconnects and lets you use that data to reliably know the exact time when the user disconnected.
Where to go from here?
In this chapter, you learned how Firebase works offline and what features it provides to help you handle offline mode and connectivity issues. You also improved your apps user experience in a way that you enabled your app to work as expected even if the user is not connected to the internet.
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.