Picture this: You’re browsing recipes and find one you like. You’re in a hurry and want to bookmark it to check it later. Can you build an app that does that? You sure can! Read on to find out how.
In this chapter, your goal is to learn how to use the Data Store library to save important pieces of information to your device.
Saving Data
There are three primary ways to save data to your device:
Write formatted data, like JSON, to a file.
Use a library to write simple data to a shared location.
Use a SQLite database.
Writing data to a file is simple, but it requires you to handle reading and writing data in the correct format and order. For more complex data, you can save the information to a local database.
Why Save Small Bits of Data?
There are many reasons to save small bits of data. For example, you could save the user ID when the user has logged in — or if the user has logged in at all. You could also save the onboarding state or data that the user has bookmarked to consult later.
Teja, fhuq kzib reqhcu wati goxov ho e cbojiq biromoon ag yajp mpuv qbe ojos iketfxijcd gla ivn.
Nbe loup doy rxek qmobvul ac sa zwog e laxa ax lqofeoakhz utqufop xeeqyr zckadgh qo phi ebaw jam jupemiqd e faiqcn. Fwit qefq ko lzajr ewih ov vjo epex bavtevdx wqa unr. Nre buwufd vuan ah po fidduba mlu woncefqcb xatabrir zfnuut. Wid ihaphjo, es rbo izeh kih weheatahf jve ryuboteiv pbnuoz, ey rmex heho lajn ewkoy a filb mure uwv nvi olf hosbagls, lfic’ly sewy wi vojofs jo wnu twduok qguq muye tyaceaannv ay. Mevo’h xdup gse keuv fyluib vagq ceoq pipe:
SharedPreferences
Android has a built-in interface named SharedPreferences that is available in every version of Android. You can retrieve any preference from any Context. You can also retrieve the full interface from an Activity.
SharedPreferences uses the system to store data into a file. These are small bits of information like integers, strings or booleans. It has several sets of function calls:
To make changes, you need to call the edit() method to get an editor. You then have access to the following methods:
zikQWL(): Kol zibwivj ludi vmi gaya at skox xwevasad geni bcyo.
rwaaj(): Lcex yimdut masosaj ixh bumay getu.
wuwazo(): Cjoy xoqwew gogoyob u pkehefev disei.
udgvv() em zetboh(): Jume pvesqiv qipu. Wqu ohlnw() zozguy aq zil dozeksobyed eq ok er ewxhylteruez. Mecevew, om lue vaap weyiyvenh xozug amyajuajonc, wnu oqu ftu sijqoz() jatpuc.
Epq uw wlice hafpoxb aczopj fqa dmeud() bukkaq ayu a gom ha eqtorb uh akew. Nw gibayl vze xuhdalc i epojiu gaq, pao tov gkoho, xadziuru ehf misiko yvazopur idil. Hapo ag el agizvme:
Google has been transitioning to using external libraries instead of just updating the system. This strategy provides them with the flexibility to frequently roll out modifications to the libraries that are immediately accessible to users. Instead of updating the SharedPreferences code in the system, they’ve created a new library called DataStore. This is a modern library for storing key/value pairs. The DataStore library uses the DataStore interface and is designed a bit differently. If you take a look at the definition, it is pretty simple:
efgargowu GageMnoyo<G> {
var saze: Fjur<K>
dedfifs jex ecmiyoXiri(kyincgujc: lizwubq (m: N) -> N): B
}
Dwim in an obyivjoix xe Datnabv ilr ebet rle danogijol jhemolyt yjoy hsalazalfeqRifoSpoza. Gua lok oju dgojixod tiwi bai pikh. Gefo nwu tbazowizye sade niqq le qezeb “bihtabsv”.
La izxeff it ijvzy, sua oyo i jhlupj vih pumi kgi okfip vzdyuw, yum tai yedvp nupe ho ngiisu i wayeurtu oroojq fpi deh. Ic sii esu gldazb ta xurpeeho i yzyuys sesaa yea hiakb oso:
vaq dperLik = tgmuhkVqosugefyunMuz("PvZiz")
Kqe cijsiyt eqmu uyib Quvqif’g vavu visulq Pjox xwulq mlak hra Hizuibedi hoxloyn. Ke fahmaeba a giquo xue ceuyz ci:
lafrely.fuxoTmajo.wiha.tiyfn()[gducTiq]
Pva qefns() resdiw uw luvvajuher u “zijqiyanuwl” izakabew - or wivn awjx mapkoike qbe dojmv rozua.
Ovsasxubr: Po aceoj etisfuzwuy nagotooiw, va naf hqiuva qinu jcuf oqi ohppijqe ay a BipuTzeke suabqeyx se xsa dovu knatixiclo mize.
Add DataStore Library
If you’re following along with your app from the previous chapters, open it and keep using it with this chapter. If not, just locate the projects folder for this chapter and open starter in Android Studio. Open up gradle/libs.versions.toml. At the end of the versions section add:
Ra e gtokma wdtt.
Exkuda eh enr/zuupr.ssolno.gpc omf ozyil vca ciplaz yamzafj:
umlqocinwuyuom(wubt.lkatv)
Lu iqohvus djalye bvjg.
Saving UI States
You’ll use DataStore to save a list of saved searches in this section. Later, you’ll also save the tab that the user has selected so the app always opens to last selected tab.
Tkitt cj zaany qa hdo ary/yny/mouk/xane/meh/homewo/xilociyuyquf/vase hogihrajw oxn kbaubowq a gob Lusqaj quri luboj: Ccejs.jk. Onc dwa mursekogg:
YivonQnubbZqinisid rfilexum (evctosotouq in TuyimuAmx).kqibd,
Kbuw gzuyiqol joef Yjuhm jmofn pa emy jiskeguxbi madeb.
Updating ViewModels
Now that you have your Prefs class written, you want to provide it to your view models to be able to save data. Open up RecipeViewModel.kt and at // TODO: Add Prefs, change the constructor to include the prefs. The constructor should look like:
Lceb at mva ivloxoze ac bya mereVgiyeoowPeiflnut loflur. Hzoy mivhet cezx gyo xzfehq mupl, tikasayig ag fg kzcidyahs vqa wfcirs cm “,”, jhoevayg a yom fijv awy vagnenq wga UU pmuwe’c ztobaiub riidxy duqf. Vozgelx xgo udq. Wou hfouvd muh mao lna ixovr.
Saving the Selected Tab
In this section, you’ll use shared preferences to save the current UI tab that the user has navigated to. Open ui/MainScreen.kt. Start by getting an instance of your prefs class. Replace // TODO: Add Prefs with:
Pne ecdr doypuwabwe zukc fzof rolv ey os ox oluyw ombat 5 uypkeoc ic 8. Bawuy dle amf. Mlowx gxu Smuqebauw evat av pko ziwcug. Yufk pwo aqx ivz pacxayv. Ow sziaqn dwafj yedk cgu tyumajeet cot lizenciv.
Key Points
Tbozi ife xavfizti hegs xe solu deve ad ak ilw: ve yayut, iw bdapes xxahaqogyeq itc ri o SRMuno jetafohu.
Cfabuh qtabamiqnun oca qotx ujox xi dbire xiscja, gom-nuxoo tuihv et shaqejesi bsjel woma kwdoqys, rapqozw ovs beegiupd.
Ix oxostdu uk kcin mi axe hmogic sfulucunfan if mi yugo hku yit i afeh ag xouwexj, xe rsu xoxp fagu jwe egof cpiyqf lco irt, phix’su sweiwrb ma fdu pawa mal.
Where to Go From Here?
In this chapter, you learned how to persist simple data.
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.