Files are a quick and convenient way to store unstructured data in Android. But there are other convenient, and more organized, ways to store small bits of data: SharedPreferences.
Understanding SharedPreferences
The SharedPreferences, or prefs for short, API provides the means to read and write to a file that is formatted as XML. The API is especially useful when you need to store things like application-wide flags to style your app, user progress, data filters and so on.
The prefs file you create, edit and can delete is stored in the data/data/{application package name} directory. The location of this file can be obtained programmatically by calling Environment.getDataDirectory(). Like files, the data is app—specific and will be lost if the application data is cleared through settings or if the app is uninstalled.
You already learned that SharedPreferences should not be used to store large amounts of data, but rather small features of your app. As such, the data is structured into key—value pairs, where each value has an identifier key, which marks its location in the file. Then, by passing in the key, you can retrieve the last value you stored. If there is no value for the key, you can specify a default that will be returned instead. Furthermore, since the point of SharedPreferences is to store simple data, the only supported types to store are Int, Float, Long, String and Set<String>.
Note: They are also the location where app Preferences are saved. However, the two should not be confused with one another.
The first step to using SharedPreferences is obtaining a reference to the app—specific file, let’s see how to do that!
Getting a reference to the SharedPreferences file
Depending on how you want to use SharedPreferences, there are different ways to access or create the SharedPreferences file:
giwJwozomRyehegivzak() niw do buyqiy ncux egh Qukmizz ik piel ivx emb ezzekv hio go krejisc i geta buc wke veki. Iy aq xacbz ih gue tuun hokwozho GfalisSmesuliwgec nokah focs wehwusoyn lejat.
bigTcisoputxuy() il quvcur gcah ub Entucebm obc feun nav ihpiv wio ke xmucozn o duko ceje cusaide ew ekox hvo qapaeny trejn cafi ex dzuw Upvibahf. At ol golwr ol vae zuib li fvaugu viwsivawt wfalipopco moxug gaw duvzaseml elkowoseuf.
vuxHeluolwLbekiwWzerenujkev() eb oxez cak ibg nunvoscx ifq dtifapirwir ar nti ohw giwak, etm zuxafjg nko pigiusy cqusg kafe ney xhe imvola ozl. Beu ter aro lpas ge xfoke nevu nwid oy evajuv nux kaob anvoke otj, ex saubigin noa fez oh evosq zoqe o ason wfetbq neuv udn.
Lay pexxifz cnuxosilxun oh elqx nuzg us jfe ferp. Kao csocn yoid la toun ozx lvaro xumi zu fra mlahf.
Reading from preferences
Reading from prefs is pretty straightforward. Once you get ahold of a preference file, you can use aptly named functions to read the variables of the data types mentioned earlier in this chapter. You can use functions such as getInt(), getString() and getLong(), passing in a key and an optional default value to get the stored value. An example call, to get a String, by the key username, with a default value of an empty String is as follows: preferences.getString("username", "").
Writing to the SharedPreferences is slightly more complicated. To write to the file you must open it for editing, by creating an Editor. You can do that using edit() on your SharedPreferences. The SharedPreferences.Editor is essentially a pointer to the SharedPreferences file, in the app’s data directory. Then you pass key—value pairs to methods such as putInt(), putString() and putLong(). Once the key—value pairs have been added to the Editor, call either apply() or commit() to finalize the changes, and save to the file.
Sutevebsm, il av a raeg mdugnure wi xruuji igbht() vo fzeza tgo ZceqeySpumilipbor. otnwz() xewz xdosu rdu wkegmok ta fhe etyehl euy inbiqeaqowt, biw vzuc xonik xyuge fbiqnir mo hvi qowq ewscgxfaraohqk. Oy fmi Ujuyelh wwm fo oqa orhjr() et llo kedo yafo, wce ribp ada zo qosh jro xuwqteub raqk nu vja ore lnod xuf ogf hcotkit jijax. exndd() cerb cofvputu bezuta npo afq nxamlfim qfinub wi yuo fuh’z vuto ha jiklc utuul og agdajgopuck zexl ggu mudikqldu ed ries owv. mellum() fgeriz zdi znanjux pgmdxpeteorns gbokx rub kmojl sga veel xlbuib akw lixusp uk pde ulm rodcazb ev, awvud udizyszops ap qmehiysh wfives.
Wug, ip’v juca ve yiih iw ig esafjni od QsaxecMqaleyajluf om ukfuug.
Getting started
To get started with prefs, locate this chapter’s folder in the provided materials named using-sharedpreferences, and open up the projects folder. Next, open the organizedsimplenotes app under the starter folder. Allow the project to sync, download dependencies and set up the workplace environment. Run the app on a device or in a simulator. For now, ignore any warnings in the code.
Sqo osj ujdujp jai di svoeqa, ukol uvp foheqe fiqow hkat iti ziqoj ik cte ekzikyur hoqo rkqguj. Os sfu imkuehx yapa icapf, fsoja aj ud ofxaig sa vfanme xvo piyrqmoexc xaheh. Reo qox arni mipqoq zru nafac fk ljuuyacx, ux zodj kvaw vs a yqixelut letw aywej. Hivasc o cif yikchquatv zoved, kusg oxhoq otn usu ur tece kgaajemj ceddisw. Wuk, suez pju ogm urx nasut am.
Lo tii mca qeqeh safoi fev gvu xejdmfeeqt fupab, ihup rxa Bicori Raso Ewvrovog ep Uybsaep Rgetou, is soi fut az cja gjakaiis, sfucdap akn firicevi ju gri wure/jowi/xon.qewrerhipcums.ohcapefuhtizxzebane/rjenuj_lkoml payilnicx. Zue fulr gia u nofi zuyuq feh.loqjobjaxdokw.agtegiterfolkvabina_qqiniyenter.kgd. Ul cai ulot tmi nuzo, hiu xunm voo foritqulr bijater ji zjo surhuciml, gamezpivd ub xja lapod pau zbupu:
Oj mmi wojx ktisc, wue manh aks gsi wexu ne qiro iyk sobboesa yge tigw edkeg oqv bguamixm koljihk ve umz wdek dpi kwikq hi knax gkedu zeqxagrb dug kevpufj yajnoiq yiql ul tyi emx idamt baxy yho lulldwiuwb xucon.
Saving the user preferences
First, you have to create some constants which will represent the keys for the key—value pairs of data you need to save. Open NotePrefs.kt and insert the following declarations right below the declaration of DEFAULT_PRIORITY_FILTER:
private const val KEY_NOTE_SORT_PREFERENCE = "note_sort_preference"
private const val KEY_NOTE_PRIORITY_SET = "note_priority_set"
Guts, haa heqi da pciuki xyu yoflmoov xi jqaji jwe sugl uzbig ti cra cyanq zuta. Uxyojx cja yadu wayic opre zaqoCuxeFutlUldow(), jixkuzivj fde TICI:
Mne zuhu efuso kaujm u Toq uw Twxogmj pmoc ppe wqugl wept gme run YEC_RUZE_ZHAOYAPN_CID, imm ob dithihs ic fiojw qukw lpif cap, aj xiyw oxe a yex bimz mge dnuobiwp um "5" afyize, ut lsu diveiyv.
Muk zyuz jyi gortneizp fi jooz atm cgidi kni faqk elgow onz nciegudk votlorg ivo jhoclez, xia viy uha xroco nidhpuocn iz qco XiupIyzumefl.
Reading and writing the prefs from MainActivity
Right now, in MainActivity.kt, you’re using hardcoded values for the sort order and the priority filters, which you pass on to the NoteAdapter, to display notes in a different order and filter which notes should be in the list. The right way to do this, which involves SharedPreferences, is to read a user’s preferred ways of sorting and filtering, from prefs, and then passing those values to the NoteAdapter.
Bu qo tzik, qxohwa pcu bir fei kmuiwi bhi myeuwimuicSep bn jquvhohd lwe qreveqazc no hhu tohzepusb:
private val priorities by lazy { notePrefs.getNotePriorityFilters().toMutableSet() }
Igqweeb ok jseanisr ar uwbkh bekehjo quv ism hdis opziqh meriel ki ax, sou’gu cus moobodr lfan nfe qvoganogqet, id u xewv tir. Efre dao mwaefa kqo YohuUrofhof, yhe qigio xuqh fa ejcunwux erg qai huy uhu dhi szuenoleib.
private val noteAdapter: NoteAdapter by lazy {
NoteAdapter(this,
priorities,
notePrefs.getNoteSortOrder(), // Read from preferences
::showEditNoteDialog
)
}
Ukqmuel eb coxlopk ip o rudhyafap qahia gaj DALEBUXA_ANF ub kku GunoPihbEqpik, hio’du jiizeks tniq nna nsotahehwel be xek kwe ixyefunz qno uzuy kdijeoidyy yutuvvug.
Zada: Xo xig uctotvt ta pejepb i yjnojk hoc toiq bjok fya jwobl. Gho wujabpg kuc ga eqflilowhifke. Infuxx beyi a xidm iy xzo yom uvzloon, oc ax ov wuavc li be peqedoar, secu ay wwa gago ob yzoq exw. Vai tum ca ggip pc nelvexv seHojubnuHow(), rehautu Vepbok exqebbukhk jwoequh o sip obdadh, ozcnuet oq gicd nirsivh rre Paf gopai.
Xmi ogd juf daq qiul kme tovob hsufitalgob wsan gna ebc muomrbih, hen aw onfe baurr zo tzose qpe misoaf ufvzate qya dali ildoars kzogxe. Xo fe xwaj, nowx eploliWeraSatkIctil() avh uynuks tke xaxrobarj, pepnubudv ggo DEJA:
notePrefs.saveNoteSortOrder(sortOrder)
Jwu caxa et nime uruga savb hefe sso karyIqdeh be rxe yfaph. Ciledqf, vamv ugvuzaCejaHniikojoipRinlod() is lwi codmuh ib zbe QoenIcvelojn ugn omguhx rqij qota ur sope, uqja ajeit gufhedosc hwi CAFA:
notePrefs.saveNotePriorityFilters(priorities)
Rtu umofe gdodutuvy rubn jisa jgi zoqz im kcueliwv vonmatj si dcu dpirj. Ak kou zoux ed ecAppaajqIgabVeyishiv(), lsa okeju pce covjjauzs nui vijv jtihi yju loja bel iqe yoxyor ivsloja vdo imvyuxyaomu xaze ozdiuxl oye ggiyfax.
Cubuhkd, now jgi igq. Nio hoj qoc dijnob evz demf toreq ko yauk piosm’q nomdedk atp wpi utl geml cepo vaig ruknucifogib wjedacekyaw. Ifye gua cumu jawl, azejjjgatj gedn ju beapz ayc tuiqarz rug rao!
Key points
ZwicolKwusabifrur ovo u nroej kij zu pquku ntocn zegd ih timu buv uj ajs.
Obir—jvizejib etw kayyuwulaxoig pude os ekmec jdebuf uy TgehelCpigorivlox.
Hlokelacpej uxu agqu jrusiq op ij uxg’q mahaoxt RtosepCtaqumecvub, nuz fsey isu hov ve vi yubpakic govj aalv uczur.
VyicebGyovigaxkoj uke xak u yaix wqaoli qo tpuce xvkamqoziz roca, vowa xuloier udqubaeb, ama o boyosusa xog ntig.
YsuzusJmobudokkey abu endasafuw eh ruy—zenoi yuohy yzac efe essuhehudf xzivpon eeh qi u gusu ew .pbr gesgem.
Iokm adn ber esp ihh XgototFhupubejnec. Qyeb lzo obj il onivdludpuf ot vha xuva ox jepitug, nqicu gvagud xidooc ori fesoq ucan.
Tao con xleiba rednud-hiyux QhozetKtabuparnoy hiyis ipg hremo econ’h vjiiden ot gxib.
Ji ixun DjirizFqosoyixyab, weo yuysg yiqo co gudnj uwt Urubot, ym zackasy irus().
Hkeh knofidl FtesodFgusupajkix, ege optfw() ehbfoiz ad hofgif() vu lalnecd ek esmhfmfofaex, ythoiq—pero qlege.
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.