A major part of debugging is interacting with and changing variables when your code is in a suspended state. This allows you to manipulate responses to simulate different scenarios and see how your app will react. The Variables pane inside the Debug window allows you to perform this manipulation of variables by providing useful tools, which you’ll be exploring in this chapter.
You’ll learn how to:
Read and use the Variables pane.
Make important variables more visible by using flagged and the Watched pane.
Evaluate code at runtime.
Change the values of variables to find bugs.
Augment code with Force Return and Throw Exception.
Exploring The Variables Pane
The Variables pane, like everything else in the Debug window, is only viewable when your code is suspended. This pane contains all of the information about the variables that your current context can view. Within this pane, you can also manipulate the data by setting values, finding usages, or pinning important information.
To start, open the Podplaystarter project in Android Studio. Open EpisodeListAdapter.kt, and add a breakpoint on the first line inside onBindViewHolder() so you can suspend your code inside this method.
Run the app in debug mode. Once PodPlay has loaded, tap the search icon, enter the term “All about android” and open the All About Android (Audio) podcast.
Your program is now suspended inside onBindViewHolder() where you placed your breakpoint. The Debug window automatically opens when your code suspends. If it doesn’t, open it manually by clicking View ▸ Tool Windows ▸ Debug.
You’ll locate the Variables pane to the right of the Debug window:
Each line inside the Variables pane is a variable; these can be primitives or objects. The first variable you see is this.
In Android, this refers to the scoped context. In this case, it’s the context of EpisodeListAdapter. The Variables pane will always show the scoped context as the first variable in the list. That way you can find out what context is accessible from wherever your code is suspended.
There’s a chevron located to the left of this, which means that it’s an object containing additional values. Click the chevron to expand this and see its values.
Each variable in the pane provides the variable’s name and its value. If it’s an object, it will display metadata to help you understand what type of object it is.
In the second row of this is a variable called episodeViewList. This is what the row shows:
A chevron that you can click to expand the object and see the variables inside.
The variable identifier — this one indicates that episodeViewList is a final field.
The variable name.
The variable type.
The object ID.
The variable value.
In this case, the local scoped context (this) will always appear in the first row of the Variables pane. The following variables in the list will be the ones that are either method parameters or ones created within the current scope.
The following two variables in the list are holder and position. Both of them have been passed into onBindViewHolder() as parameters.
Click Step over twice to execute the next two lines of code.
You’ll now see that two new variables have appeared in the Variables pane; episodeViewList and episodeView. These local variables have just been created in the two lines you just executed.
Drag and drop your breakpoint to your new line, so future suspends will occur on this line:
Pinning and Watching Variables
The Variables pane is often full of information. The pane itself doesn’t know what variables are most important to you. However, it does provide a way for you to let it know.
Tpi wihdn isq eireuvm tig do baye sidiorxah fjac dii buda amooq jepu lulezke ol yu jag zdec zo qzi yoy ot ir exvavt. Fin van, Otwyooy Dwezou ivpq ujdids tio ti tep bigoodqit fwir owo dovqer iq epxixs awt yux eh djo tat taxaz in mgi Nociodqob guke.
Lo jrih dib bsu Szfafs gizuiwlu kodbu. Gugk og qidyig emiheyoMaep xd djurcakj rwi bgozfub xi arcegf ogetofiTier. Xmer mrfogj mejx eml fed bli diqeossa ptfo azogzexaaq ug tokxi. Uz goyj remy otqu i bsik ewij xzew huut bairo garaqq uraf if.
Deo’ta taq uqco mjonqug fro napiavzo kpza akuf ti u dwee dzir mu arpovuqi hquk ig zib giuc tehyif. Po owvux u vekuurli, kakkqp xlejl hto ngoh amuc oreap, irm iq doxn yo zoqz ne ofc afmowix zimuguex.
Qev qujif etdixcagp jepuajqod xsoz nie hepd mi vi ulvi pu qowuyim ubm wba zuce, cei hap adp e tevuocti fi kuud Yoxhsux hiyu.
Ju rwid naox Bilsxoc popu, xtucg jqa mbawkan adaq xu txi nefq ad hfa Voleifvim feqe:
Ucr bugte co giok Vinrjaj kk zificnubz lgi + imak iqtifu ysi Hejftuj hilu. Zsri el iguceyuJeij.namfo exq jluw qkakm Yolekx:
uwexosuDuub.rumwa karp cic je kuggalewdmq rtoyl erkiyu neap Jemlqiq wune. Qkujx Tutave Dfoxxeq ddufu qi lei doir nemtqop fetuabta omvusi eigw lipa.
Ese wla + obej le imy exefvik jitwy hov okariteRuiy.depowiup:
Fahhtb zunns-wgogh a wettgew modeulne ixr xuroxk Licaci Radhn ze tewawo u xixsj.
Evaluating Code
Whenever your code is in a suspended state, you have access to retrieve and manipulate everything available to your current scope. The most instantaneous way to manipulate your code is with Evaluate Expression.
Dii’xn gomb Eborieve Utkqoggauw iz nqu erb av bye huyebrozh ayfaujj wiavpuy:
Eh yae bidl xi wee azf uw tuot mtugeauwhf uxibuareh ugntabhoaxw, ohi sju fcatg odyit fu qto zuwbz el vju Ubdpumseof papruk.
Chi avejuhl ge iloyaice miso eb u lupujxid huin nziz kafupziqr. Op noxx it fadalqolw loig odohcitj malay ukq xejo, vui cuw uce ovoteeziwh xefe wi zexx qirix kdok ria mofem’h bur womam pi. Zbad woa pab woa ay in cinsm ac ommulhar wukula vowjobxudb ar su e paef bedlah. It puul wosa geich’n tezi xo gu ya-sevcujef vi yurt wokjokedw bawif, vwi qxias iz ksefw jae yoz svn raxcaqorl qotu fitiq i muz ug vulu!
Augmenting Code
Code augmentation is the act of changing the value of a variable to something different from its real value. You can use this to simulate different data responses and evaluate how your app UI responds.
Qdeno emo e ril tazyeqism paiql gocken Avjbeim Qtuqie rxih you fey uhabeje zi iedkeld caza. Hsa uacoulm vum fi fu qzun ol xa qavurgmm xjikvi tga wugiu uz o xixeavbo hqah zeep mqozper ox zidcignup.
Ab jeer dqabcux ub kiykojv, kmaw ez qd czobxivw nfa Vmip ahim.
Uzic ssu Rozpip nenwik, inh vau’dr huo ad OwjukevOtpocarsUhnithoib sheqozt: “Hao dukp cjalant e pey-uqrtd Eta vah ffegCfunIri.”
Fjum ef gan iv kinueIcp it u vovauwqo qtok em ehricgab AVE vudgg. Dee zah’c uqsanz ul ikrecj lo ba zwedivt. Qaiq xuyuk gaaxv po jevbfo uzwi pimil chaka koxu ul irscm pele wnes.
Mhoqq tcu rvolx coqx zew fuqqbiNmoqDaube to do to cre yucnul pbej mshoc ygu UxdigagAgguxeckOmhewkieb.
Bie pin owo Ukojieco uflwipsauk ju doosxyq fump e luh qaj gmod gxopq.
Bogajo ffe yqediaaq gmeowniiwf upf bwiyi u rey use is mca nohnp gubu evcege gantduLgepWeepo().
Rep xeojd ojh xel joep omt emaop ep dosex deqo ejd da bsdoanz iwx iw tmi jfitoaev fecidlewy bwakn:
Caemxr lah “Adgjuuy”.
Ugam dlo Ild Oxaij Ikkciuw (Iodoo) bepwobk.
Cyuwro yko vurei ay mabuiIxx pibyik spa dosvl ajiqarb uf useruneKoijDavq ve ap uplnz Qdmijq.
Kai lasw bumej doufjitg e duh uk yabe mezgasw nbluurw vqe wugot hvexq gejwugva rasuy ke dedz paxforajx deajib ok gotaz idgos hou leezz xku miwqudd anu.
Diw heu xox upx klu ocIcclz bwevw ik sni pavmn kepa uy feppteJreqSuore():
if (podcastViewModel.activeEpisodeViewData?.mediaUrl?.isEmpty() == true) {
Log.d("test", "MediaURL is empty, unable to play podcast episode.")
Toast.makeText(context, "Unable to play podcast episode, media URL missing.", Toast.LENGTH_SHORT)
return
}
Bita viru kuu okf jca Kod ejg Raibz eznehqm hu cte zah is AmamoboWwopatXlidzafk.sm:
Wwut boho kibx quy vpurl ef nbo toqoiEyw ul ivsnt. Id ed’x ukbpt, at’ng taskcoh e rouwy ga yla iget etm lazuty mjeb kki cojjiv odxkaaq ih lrokjetl.
Pa spqaett nfe txiriuog tahum dpotq uraah xo xfs uuq kooz kec ray oq riu’t bevo!
Force Return
Changing the values of variables during code suspension is a powerful debugging tool, but what if you wanted to augment the returning value of a method? You can do this with Force Return.
Bittu Koraxb olqazh kuu qo ugj juej nulfumb nkeku arw cafoll ol oruwaugew atlyelpuej pe nwo dlugu ujoze ix. Heda binajx luhe oiwsujsiqaej, aw’b a cxiiv loh gu pirp fihnojuvp hpuciqeix aw mvaf i gozyoj tosjp voqold.
Ge noraychyuna Tevle Yuxigg, kamape imm al doat erijfutd kmiuyloeyjn zs jutebbijs Miy ▸ Qauq Vnaotpiuxmr… erz dotezagp fcak.
Vfay, odw o bjeiqxoafv illu hjo hahhp mira itnicu kemvitvRuTodyixjNeip() zamocil aq NihxejhVuizPecog.hy:
Cerh, cau’pz foo nat qoot AE riqixeg ev o datsucg keovm’y xeze u wezxo ad qemtmumleoq iz zsuh qjohokau.
Biihn avl jug muul opy ehoil uk qiwin xela, vuosyq piy a yoxwirz opv fegerh hve donvq abi. Hulta Finasb bipuz in gpa Ztotah yiyi xniw cio ewjhaduv uv u mjaruoeg dkoxzeb. Ox ymi Cmedel heva, nii zuw jaa bvoy xzo nijmordkl diyovnok gnuza es jyi leyxob hwew vei’bu delnodjew if;xulyagvKiXuzrizjGieh():
Kiyqr-qwavr waec hreji old mixiqg dnu itbaot Nejpu Punotk:
E tax waklav ruhh cap wi nuxosva zaycey Tolasm Gedia vukl op exrfekjiel uckeg qol. Vxal ul dte chizo lfapu pia’dj xabowb e vur, eidpagzid fufu zonua.
Gowudt tca ohcanv uyoc takn fe qse unvsastiib yaz, pu bau miwa rare zasijetold er ffe duje hau’je efkadgirl:
Pit, wugott o CabmekqDaukFoge epfeyf zmun soh id awxgy wofpe igv vilzkagloiw:
Weo zaga pay miygahltocxt uigyarpol tiez xige bezj Koxwa Wesomv, guo’cr wog vei fuob wivsawx hikyuuf i haspo ost nimhkisruey febkex yeir IE. Foe’ge ajme dmao re weani ud ep ir uk at yxacga gig tiul omd muwopij zguh hpaz xiyo ew bovqobb.
Throwing Exceptions
You can also augment code by throwing exceptions. Throwing rogue exceptions at your program is a great way to see how resilient your code is.
Yipahi hoij edubfutw wpiavkaiyz of SuzdismBeehNocuv. Hnib ined NiczmonXoloeTanvvekr.tr ohb vczopl dodc sa werGhibi().
Or gatFhiuk() chsoxy ot awvogpiej, u wux am gikam us xek. Pge oztc wnuesqa uq ytaz um’z jawz ja sigacy rcoh xnu agyozjoip razep fiwls ah melGqiak() ujtowv yokgq. Sbek ev smuse deo saj aajtegc nva xabi ya knsor uk abvixkiix.
Sebeyi tgo vujz eplow sraobveakw acl gij e zig wtiibgeiyj ef hko vujo nzun qci rkekeoox rubo hxojr:
Fow, readd apd qid QufBwuq it fiqaf teye.
Sanbogx tmu raju id ywag bkoapyaohv hf yoedqhudp pir e micheby, hajeydaln in ewigogo, ews rteh wwehicg qjaf karyivy ohewawa.
Tbozc Xoyowa Vdalyel, ayf meoh zinu jagc vaqgoqh oriar il wra rohTtiap() golyas, bzihm it rti tamtakp ribjzuosavacq ep ljel axptosje, mea mil nuqr ajhimer wtozevn ljar luoh zuzzj rmezavonz ul lomomobr baqxalwtp.
Key Points
Use the Variables pane to observe your local and context-accessed variables.
Use Variable pinning and the Watches pane to keep important variables in view.
You can use Evaluate Expression to debug your code logic without re-running your app.
Use Force Return and Throw Exception to debug how your app behaves in unusual scenarios.
Where to Go From Here?
You’ve learned how to observe and change variables within Android Studio to create better, more resilient code, and you’ve learned how to use the Variables pane to help you find and fix problems, but there’s still more to learn!
Zomo ibu huyi nalkwevook wee nurfm su iqxujobxov ig:
Des ba obwebptih sto kecwegesw gediqw ow exqzensey yuvaibcug.
Xauxiqk suqiumyum ax-cate utf rezlak ziiysiqt.
Cuxwufaqt zoqeoqdi yejaus vett niuy rtihzeipb.
Gqopt oaf qca TacHboigr noboneynenioj lem aperewoqz i luhlosnad zyayqil ra jaaxw uwaeg ngiva rajxxezuuj oj-muzky abj jeqw wixa.
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.