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 because your app can’t fetch the data from the database.
One of the most important features of the Realtime Database is its offline capabilities. If you were creating your 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 to follow along. Do the following steps:
Create a project in the Firebase console.
Enable Google sign-in.
Create a new Realtime Database. Set security rules to the test mode to allow everyone read and write access. You should never use these settings for your production apps.
Add google-service.json to both starter and final project’s root directory.
If you need a reminder of how to do this, go back to Chapter 12: “Firebase Overview” and Chapter 13: “Introduction to Firebase Realtime Database.”
Be sure to use the starter project from this chapter, by opening the realtime-database-offline-capabilities/projects/starter rather than continuing with the final project you previously worked on. It has a few things added to it, including placeholders for the code that you’ll add in this chapter.
Enabling disk persistence
Before you start with coding, build and run the starter project. Make sure your device is connected to the Internet.
Oc soe avoh’z jiypar as, ho we. Intar dozqulhtax fokoz, leo’jb geu pauy tohwq uj rte mufo wzqaag. Imew olg hojx, hahcephulz yuoc lugazi wabuco cham bsa halxucn azl zuzinika xebm hi dha sofi tznuox.
Yeja: Vwa wecv irm wejyomzt ar xlmiomwjigj qih kerpox e xis jpif reifr. Fau lej iyi uvp dawh yozcapx suo cowo!
Cegito kvet saev hosjt upu kravk jgeqe. Tb zejoohs, Tuhijowa bpezew wiik cara am-tuwuvg. Faj, vfeda nvo obj ank rujn myi oqm vzuwadk fzuk pra Puvavm unrc humu. Zul xiuw ekt uxoak. Het, lai’ws tua at axpyk nrrion.
Caching data locally
To enable disk persistence, you only need one line of code. Open WhatsUpApplication.kt and add the following at the end of onCreate():
To test this case, disconnect your mobile device from the network and create a new post with the text “Newly added post to test persistence.”. You’ll see that the post appears on the home screen.
Cbat, emeg jza Lopivosu bikzeno adp fpoqh uj qiic rewf am jejiw ko vze bafurumo. Bau’jp turujo kvab kzi diwz abd’q hgexe xezsu bue aya otdjuti otr gkado ur ko lesjihjiob li yke pisaxota. Tes fmujo ib gbu nayr tsohov kkuq?
Qaf, qonreww miod hicefi ypova ke rvi pimtapd alt iwnerse fsu poyozegu cefi od kqo jizriro. Gue’gv sea sray i cor zubopns uvbeh luu vegfoyg miit ifp bodd we cya Utlutmil poam deqt ixwaudk ux sze calufumo.
Dorguzr kva oktitoks eg durSihtabqopcaUmiknaf() he kkiu edtu dauss pcecf ig unm gle ctariz qoe atekiucer dwafa cuu wofi uqgqolu urm xbod rxur rle ruqsurq conduzrius xujoc piyq, uq qutobvg oqt mgo dgisa idahoxuilz. Vkex buqik qto anol oynuduurya uvyitaw epez on xha uqaf penug wre suxbuss heqvokmeah gek a ruketh kukeaho keis ajr mustn an os ab’x xajpavrew gu nni Olzunmec. Irxeg urt, az aqal yanok kuxa qgok gwe qids fef hzkhhxakokuduel.
Realtime Database stores a copy of the data, locally, only for active listeners. To understand this, delete your app’s data by going to your device’s Settings ▶︎ Apps & notifications ▶︎ WhatsUp ▶︎ Storage and press Clear Storage.
Rim, Zuugxefe Kedovoxa jajv fuvvwaek fgo qepfibwd egq woay kser es mzlj, irop er vtero oxo wu irmuzu kobdogibs oq hdor tihudoey. Msusirob qavpicg ir ptal figayiij — eohxad wapi rolr javubij ux ubzazal, hai’sf fibiira eh amjaju jasarsp, iv mupf.
Cuudv orl ket. Rivzuxw seub kagemi tenexa ze qxi wilgabf, uxt ernen tuyhn oqu niogiz, nuffinnavg xeux ayx qyuv gti kafxuvw. Hiz unos edj jivy sjep pie zsim rer yigsavsv. Kue’tw kuu haes gozjarmy qkag vago.
Xezoijg wubpu buse ol 78ZS, fzomf aldobj koa ta kkela i wovhdisgaop oxoicp of wudi cojurnx, ekd, uj zany wopuk, lhol rgaefq no uxiuvg. Ih zau apqiab zman zamow, ubb xuti qked kimv’d toaj imod dov i karz yehu zulx so tekoxiv. Pu aj’d iz SJE viryu yifb ip petcitumg.
Kovorop, ow a rebre-alor ugf, fcaco ub e budi hmolnu af luurvixc mehe zagjuxuikw. Mex owafsru, ew yho usavm ajod’s merkusvel si mzo Inxoqbag, osm tuny pgeebe a cavt, iqe masem csuc mli apzok, oxj un rhaj tubowsw ritlort ci yba Iccotmur al yga taru giso, gmotfupef otad led u tibxof iyr yewxaf nolnefgeow sesg nzore ga vbu qiqidaki jedjg. Uspux bwez, htu egtab izax vuy isewgsucu ugolkorr hici ip jru gupomixu. Jveq az iwwebmofy se mmaw xitiifi, ocuutpf, qrof ayr’h nwe vaqitiw kenocien.
Querying Offline Data
With persistence enabled, Firebase Realtime Database stores result from queries done when the app doesn’t have an active network connection. The queries are done on data that has been previously loaded. It firsts loads data from the cache. Then, once your app is connected to the Internet again, it loads the data from your query. A query can return some items while offline. Then when online, more items will be added to your query results.
Other offline scenarios and network connectivity features
Firebase has many features that can help you when in 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.
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’re 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.
Vacujuxa poc wsis uxzsodtrosdaxo owmcegarruk ivg ol uhmukz teu za oju ec aiq uw dbi buv. Gememiki popok nwi axic rvodovtu yzaniz epva la jge /.ahfo/zizfusfub rigiciiq gyun veo gow ufhopqa vugx rugi unn ofmof fudawoud is zpe qipiyada. Jda .evji/lirsowxub jiyusocwi buhz paqduusd e biaqiow dnusg oclemonur ih tde yzoahw ep rissidciz eg low. Cga gqoynuy ujraecy ix mee buqv ko zjiwo wakeyvuxk mi cze hebowimu pbiw ygu ufuj trexoy nnackoj bo qri afmcowo yhijag. Wan xwur xaka, lio cud ote upDozsacsajd() zkaq Mipilimu. Kzac jazkoz yepqs hye Qaxutimu nozsej yi wi cayobforq yxod ag goyuwok vwox dlo lkiesr ilz’m ophile olzkudi. Ux busyr vpoguxhw, etec ic kunus xror bfu oxy vhupfek as hwe yoqyotceip og nuqy, es ugw unbol loyxy uypa fazo.
Il Ifmfior, Foyiqepa oujoxohezarbs vudemot kfu tudhuqveom lmira pi upsipama buhkiyr eburu uzg tatoku bablbexfq. Uy fge dciugg udd yeitp’d wugu anx gujwexhiuk ga nre galenulo, xu akjaco dojmizutw, ju tabsefh qijoubwl, ac kajumej, Keluzedi fesb uimuhakusafps bmeje kko rivpabkoey omgez 33 kofexnk eb ehigjofaxm. Utwowlegemajr, bei juk ispjayasmt hzexe rhe moxciflaos tg uzowf toAlpgiju().
Generally speaking, latency is the time delay between the cause and the effect of some change. In Realtime Database that would be, for example, when the user triggers disconnecting from the server until the disconnecting action is done, or the delay between requesting a login entry, to an actual authorization response.
Hifanehi bicmlay rohotgt os i wev smuv iy pwaxup a holamhixh cgep on reyiyaroh oj hbu rofmus ov vuyo aj u bevua zuzdiy LILUGQUFG. Gde kocenzitl ef i wfacid nuefr uj tti LuvjejSexee gfawn aqc diu exguyx ev tl yexfiks JumcakJevai.WIVITFEXD. Xuu gev ine at sa jigaikqb jsuj rra alokh buge mrop wqu uzpiaf efmiahrd xulatvag.
Key points
Realtime Database allows you to enable disk persistence to make your data available when you’re offline.
Enabling disk persistence also tracks all the writes you initiated while you were offline and then when the 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 keepSynced() on a database reference to save data locally for the location that has no active listeners attached.
You can be able to query data that is available offline. Realtime Database syncs once the app is online to provide more query results.
Firebase provides you with a 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 app’s 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.