3.1: The Android Studio Debugger
Contents:
‘+ Introduction
‘+ About debugging
‘Running the debugger
‘© Using Breakpoinis
‘+ Stopping through code
Viewing execution stack frames
Inspecting and metying variablos
Setting we
Evaluating exoressions
‘+ More tots for debugging
+ Trace logging and the Android manifest
‘* Related practical
In this chapter youl leam about debugging your apps in Android Stu,
About debugging
Debugging i th process of finding and fixing errors (bugs) or unexpected behavior in your cade. Al code has bugs, from
incorrect behavior in your app, to behavior that excessively consumes memory or network resources, fo actual app freezing
cr crashing
Bugs can result for many reasons:
‘+ Errors in your design or implementation,
+ Andvoid framework iitations (or bugs)
‘+ Missing requirements or assumptions for how the app should work
‘+ Device limitations (or bugs)
Use the debugging, tasting, and prfling capabitis in Ancroié Studio to help you reproduce, find, and resolve all ofthese
problems. Those capabiltes include:
‘+The Android monitor logeat)
‘+The Android Studio debugger
‘+ Testing frameworks such as JUnit or Espresso
+ Dalvk Debug Monitor Server (ODMS), to track resource usage
In this chapter youll leam how to debug your app withthe Android Stusio debugger, set and view breakpoints, step through
your code, and examine variables.
Running the debugger
Running an app in debug mode is simiar to just running that app. You can elther run an app in debug mode, or attach the
debugger fo an already-running app.
Run your app in debug modeThe Android Stugio Debugger
‘stat deoviging, clek Debug 3 inne toobar Andro Stud bute an APK, sgn it wha debunk. on
Your sla deve, then ns and opens the Deg window
D Ome (leone sits Ex 2
1 ron - RE Bvt Sema s
at peer ve reyescviyoss
Brnsressrin- t+ 77 Sth Mun v
my Pee pa eee @mControlsFragment = null
e Dramatis
a @ mCastMtanager = VideoCastManag LD
Miuisasiameniiiietetad © eysaeaer- tesco
? et od Gavalang reflect) |W maudioFocustventHandlerDelegate = /AudioManagersFocuse,
eodeévoner Tem RE ne tn SAR “27000 Tag ect
Debug a running app
If your app Is aeady unning ona device or emulator, stat debugging that app with these steps:
1, Select Run > Atach debugger to Anerld process orccktne Attach Fhe on nthe toh
2. intre Choose Process dialog, select the process lo which you want to atach the debugger.
‘By defaut the debugger shows the device and app process forthe current projec, as well a8 any connected hardware
vices or vital devices on your computer. Select Show all processes to show all processes on all devices.
4. Click OK. The Debug window appears as bere.
Resume or Stop Debugging
Te resume executing an app ater debuaging slat Run > Resume Program or cick the Resume icon,
‘To stop debugging your app elect Run > Stop or click he Stop con Hl in tre totba
Using Breakpoints
/Abreakpointis place in your code where you want to pause the normal execution of your app to perform other actions
such as examining variables or evaluating expressions, or executing your code line by line to determine the causes of
runtime erors
Add breakpoints
To add a breakpoint oa ne in your code, use these steps:
1. Locate the line of code where you want to pause execution,
2. Click in the left gutter ofthe ector window at that ine, next tothe line numbers. Ared dot appears at that ine,
Indicating a breakpoint
You can also use Run > Toggle Line Breakpeint oc Conto-F8 (Commans-F8 on OS X) 0 set a braakpoint
It your app is akeady running, you don't need to update ito add the breakpoint\Wnen your code execution reaches the breakpoint, Android Studio pauses execution of your app. You can then use the
tools inthe Android debugger to view the state ofthe app and debug that app as it runs,
View and configure breakpoints
To viw all the breakpoints youve set and configure breakpoint settings, click the View Breakpoints 8® icon on the left
‘edge ofthe debugger window. The Breakpoints window appears,
eve srakpoins
+- 800 Line 62 in MusicPayerAciviysava
© java Line Beakpoints ee
1 Unese nmusiemayene 2 PSE
“@iava exception Beakpoim 2 Suspend ll © Thread
(@ exception sreakpoints Saal
og evaluated expression a
Pal error Chass titers:
“
B
Oona enable Eos
ae
s Anitistierranreraretsmecinetaneetites geetneere
In this window all the braakpoints you have sel appear in the let pane, and you can enable or disable each breakpoint with
the check boxes Ia breakpoint is disabled, Android Stusio does nat pause your app when execution reaches that
breakpoint.
Selec a breakpoint from the lt to conigue its settings. You can configure a breakpoint to be disabled at fist and have the
systom enable i after a diferent breakpoints encountered. You can also configure whether a breakpoint should be
slisabled afterithas been reached
To seta breakpolt for any exception, select Exception Breakpolns in thelist of breakpoints,
Disable (Mute) all breakpoints
Disabling a breakpoint enables you to temporarly “mute” that breakpoint without removing i from your cade, If you remove
' breakpoint altogether you also loge any conditions or other features you created for that breakpoint, so disabling itcan be
2 beter choice
To mute al boakoots, click the Mute Braskpotnts © icon, Clckthe eon again to erable (unm) a breakpoints
Use conditional breakpoints
CConeitonal breakpoint are breakpoint that only stop execution of your app if the test inthe condition is rue. To define a
test fora conditional breakpoint, use these steps:
1. Right click on a breakpoint con, and enter atest inthe Condition fl‘You can also use the Breakpoints window to enter a breakpoint condition,
wy cee ye CREASE
mi as
Line 107 in MainActivity java wt
ro} re
Enabled
Suspend All © Thread
d More (4 38F8) Done |
i GROUP rea RO see ESE TIT TENET ETO |
‘The tast you enter inthis fld ean be any Java expression as long asi returns a boolean value, You can use variable
names from your app as part of the expression.
Condition:
er
2. Run your app in debug made. Execution af your app stops atthe conditional breakpoint, ithe conlion evaluates to
true
Stepping through code
‘ator your apps execution has stopped because a breakpointhas been reached, you can execute your code from that point
Cone in at atime with the Step Over, Stop Into, and Step Out functions.
Touse any of the stp funtons
1. Begin debugging your app. Pause the execution of your app with a breakpoint.
‘Your app’ execution stops, and the debugger shows the current slate of the app. The curent line is highlighted in your
code.
2, Click the Step Over = icon, select Run > Step Over, or type FB
‘Step Over executes the next tne ofthe code in the current class and method, executing al ofthe method calls on that
line and remaining in the same fle.
™
3. Click the Step Into
con, select Run > Step Into or ype F7.
‘Step Into jumps into the exceution of a method cal onthe curent Ine (versus just executing that method and
romaining on the same tne). The Frames view (which youl learn about inthe next section) updates lo show the now
stack frame (the new method). the method calls contained in another class, te file fr that class is opened an the
‘current ine in that leis highlighted. You can continue stepping aver lines in tis new method calor step deeper into
other methods:
a
‘4 Click the Step Out — icon, select Run > Step Out, or type Shit-Fa
‘Step Out finishes executing the current method and rtuens tothe point where that method was calle,
6, Toresum nora nection ofthe pp, select Run > Resume Program or clekthe Resume 2 ion
Viewing execution stack framesThe Android Stuio Debugger
“The Frames view ofthe debugger window allows you to inspect the execution stack and the specific frame that caused the
current breakpoint to be reached,
co |e EE
nsrenstancSat 190, stumetaon dota)
eed nda itatows.n ve
Tos pane REBAG] 7000 ep haceawoms ereinf Tea Veien coms) Mpg = eeteg
@rviags «512 No watch
‘The execution stack shows all the lasses and methods (rames) that are being executed upto this pont in the app, in
reverse order (most recent frame frst). As execution ofa particular frame frishes, that frame is popped from the stack and
execution retums to the next frame.
Clicking a in fora fame inthe Frames view opens the associated source in the editor and highlights the ine wnere that
‘ame was intaly executed. The Variables ané Watches views also update to reflect the state ofthe execution environment
when that ame was last entered.
Inspecting and modifying variables
“The Variables view of the debugger window allows you to inspect the variables available at the current stack frame when
‘the systom stops your app ona breakpoint. Variables that hold objects or collections such as arrays can be expanded to
view their components
Te Variables pae also sows you to evaliteepresons on hey ting sa methods andor variables avadabe
win the laced Fae,
ithe Vales vow no isl cick th Restore Variables View on
coe G0 ED
> como oectae t=
snuck t+ 7] Sts = MinActivey@4670)
fe: Recess = oroenso7 1 er
> @mCaconde = ote onere4738)
© | Pefemserenstancesia eens
knoll Sirus Armaan sae
a Ssertvcnn df» Bitte. anot) me ado tine None
sirens. sc | gy mtaoteten= eiconprerie7) add aippon? dp ApCnpA. on
aves bstn [REBEL Toco Semester memns Wpvesen Cen! Re Mone en
“To medity variables in your app as it runs:
1. Right-click any variable in the Varables view, and select Sot Value. You can also use F2
2. Enler a now valu for the variable, and type Return,‘The value you enter must be of the appropriate type for that variable, or Android Studio returns @ “ype mismatch
Setting watches
The Watches view provides similar functonaly tothe Variables view except that expressions added tothe Watches par
persist between debugging sessions. Add watches for variables and fields that you access frequently or that provide state
that is helpful forthe curren debugging session
To use watches:
1. Begin debugging your app.
2. Inthe Watches pane, cick the plus (+) button.
Inthe textbox that appears, type the name ofthe var
ble or expression you want to watch and then press Enter
Remave an item from the Watches lt by selecting the item and then eicking the minus (button
‘Change the order of the elements inthe Watches list by selecting an tem and then clicking the up or down icons.
Evaluating expressions
Use Evaluate Expression to explore the stato of variables and objects in your app, including cling methods on those
objects. Te evaluate an expression:
4. Click the Evaluate Expression icon, o select Run > Evaluate Expression. You can algo right-click on any
variable and choose
faluate Expression.
he Evaluate Expression window appears.
2. Enter any exoression into the Expression window and click Evaluate,
“The Evaluate Expression window updates with the result ofthe execution. Nota tha the result you gat from evaluating
‘an expression is based on the app'scurent state. Depending onthe values ofthe variables in your app atthe time you
‘evaluate expressions, you may get diferent results. Changing the values of variables in your expressions also
changes the current running state ofthe app.
More tools for debugging
Android Stutio and the Android SDK include a number of ater tools to help you find and correc issues in your code,
‘These tools include
‘+ System log (logcat. As you've learned in previous lessons, you can use the Log class to send messages to the
Android system log, and view those messages in Android Studio
Torte log messages in your code, use the
Log lass. Log messages help you understand the execution ow by
collecting the system debug output while you interact with your app. Log messages can tll you what part of your
application failed. For more information about logging, see
ing and Wiring Logs.
‘+ Tracing and Logging. Analyzing traces alows you to see how much time is spent in ceriin methods, and which ones
{are taking the longest times.
To create the trace files, inclide the Debug class and and call one of the stariMetho« Tracing) methods. Inthe
call, you specify a base name for the trace fles that the system generates, To stop tracing, cal
stopetho« Tracing). These methods start and stop method tracing across the entire vitual machine. For
example, you could call siarMothoc!Tracng() in your eth’ onCreato|) method, and eal stop Vethod Tracing) in
that activtys onDestoy() method.
‘+The Ancroid Debug Bridge (ADB). ADE is a commande tool that lets you communicate with an emulator instance ot‘connected Androi-powered devies.
‘+ Dalik Debug Monitor Server (DDMS). The DDSM tool provides portfonvarding services, sexeen capture, thread ane
heap information, logeat, process, and radio state information, incoming call and SMS spoofing location data spoofing,
and moc.
‘+ CPU and memory monitors. Android Stud Includes a number of monitors to help you visualize the behavior and
performance of your app,
‘+ Screenshot and vdeo capture
Trace logging and the Android manifest
‘There are mutiple types of debugging available to you beyond setting breakpoints and stepping through code. You can also
Use logging and tracing to fin issues with your code. When you have trace log fle (generated by adding tracing code to
your application or by DDMS}, you can load the log fas in Tracoview, which displays the lag data in two panos:
‘+ timeline panel = desentes when each thread and method started and stopped
‘+ Aproflo panel ~ provides a summary of what happened inside a method
Likewise, you can set android:deuggable inthe tag of the Android Manifesto *:rue* , which sats
whether or not the application can be debugged, even when running on advice in user mode. By default, this value is set
You can es
1nd configure bull types in the module-evel build grade fle inside tho android (block. When you cr
new module, Android Studio automatically crates the debug and release build lypes for you. Although the debug build typo
‘doesn't appearin he build configuration file, Android Studia configures it with debuogable rue. This allows you to debug
the app on secure Android devices and configures APK signing with @ generic debug keystore. You can add the the debug
build type to your configuration i you want to add or change certain settings.
All these changes made for debugging must be removed from your cade before release because they can impact the
‘execution and performance production cade.
\When you prepare your app for elease, you must remove al he extra code in your source fs that you wrote fr testing
purposes.
In adaition to prepping the code itsel, there area few other tasks you need to complete inorder to get your app ready to
publish, These includ:
‘+ Removing logging statements
‘+ Remove any cals to show Toasts
‘+ Disable debugging in the Android manifest by ether
© Removing android debuggable atvibute from applications tag
+ Or stting android:debuggable attribute to false
Remove all debug tracing cll rom your source cade fles such as startMethodTracing() and stopMethoeTracing)
Related practical
‘The related exercises and practical documentation isin Actos Developer Fundamentals: Practica,
‘+ Using the Debuaoer
Learn more
‘+ Debug Your App
‘+ Wite and View Logs
‘+ Analyze a Stack Tracea4
‘The Android Stusio Debugger
Android Monitor
Using DMS
Android Debug Bridge
‘Android Monitor Overview
(Create and Eat Run/Debug Configurations
‘Debugging and Testing in Android Studio (video)
1053.2: Testing your App
Contents:
‘+ Introduction
‘© About testing
‘Setting up testing
‘© Creating and running unt tests
‘+ Related Practical
‘+ Learn More
In this chapter you'll get an overview of Androié testing, and about creating and running local uit est in Androié Studio
with JUnit
About testing
Even though you have an app that compiles and runs and looks the way you wart toon different devices, you must make
sure tat your app will behave the way you expect tt in every situation, especially as your app grows and changes. Even
if you try to manually test your app everytime you make a change —a tedious prospect at best — you might miss
something ornot anticipate what end users might do with your app to cause it al
\Wrting and running tts is eral part of the software development process, “Test-Orven Davelopment” (TOD) is 2
popular software development philosophy that places tests atthe core of al software development for an application or
service This does nat negate the need for further testing, t merely gives you a solid baseline to work with
Testing your code can help you cach issues early in developmant—when they are the least expensive fo aderess — and
Improve the robustness of your code as your app gels larger and more complex. With tests in your cod, you can exercise
‘small portions of your app in isolation, and in an automatable and repeatable manner. Because... the code you wit to test
Your app doesnt end upin the prosuction version of your app: i ives only on your development machine, alongside your
p's code in Android Stud.
Types of tests
Android supports several diferent kinds of ests and testing frameworks. Two basic forms of testing Android Stuslo
supports aro local unit fests and instrumontod tts
Local unit fests are tests that are compiled and run entirely on your local machine with the Java Virual Machine (JVM). Use
local unit tess o test the parts of your app (such asthe internal lagi) that do not need access tothe Android framework or
‘an Android device or emulator, or those for which you can create fake "mock" or stub) objects that pretend to behave like
the framework equivalents.
Instrumented tests are tests that ran on an Android device or emulator. These tests have access tothe Andro framework
{and to Instrumentation Information such as the app's Con's. You can use instrumented tests for unk testing, user Interface
(UI testing, or ntogration testing, making sure the components of your app interact correct with other apps. Mast
commonly, you use instrumented tests for UI testing, which allows you to test that your ap behaves correctly when a user
Interacts with your apps activities or enters a specific input
For most forms of user interface testing, you use the Espresso framework, which allows you to write automated UI tess.
‘You earn about instrumented tests and Espresso in a later chapter.
Unit TestingUnit tests should be the fundamental tests in your app testing strategy. By cresting and running unit tests against your
code, you can verify that the logic of individual functional code areas or units is correct, Running unt tests after every build
helps you catch and fix problems introduced by code changes to your app.
‘unittest generally exercises the functonalty ofthe smallest possible unit of cade (which could be @ method, class, or
component) ina repeatable way. Creale uri tests when you need to verily the logic of specific code in your app. For
example, if you are unit testing a class, your test might check that the class i in the right state. For @ method, you might
test ts behavior for afferent values of ts parameters, especialy nul Typical, the uni of code is tested in isolation; your
test monitors changes to that unit ony. A mocking framework such as Mockio can be used to isolate your unit from ts
éependencies.You can also write your unit tests for Ancold in JUnit 4, a common unt testing framowork for Java code
The Androi
Testing Support Library
‘The Android Testing Support Library provides the infrastructure and APIs for testing Android apps, including support for
JUnit 4. With the testing support brary you can build and run test code for your apps.
‘You may already have the Androd Testing Support Library installed with Android Studo. To check forthe Android Support
Repostory, follow these steps:
1. In Andoia Stutio choose Tools > Android > SDK Manager.
2. Click the SDK Tools tab, and look forthe Support Repository.
3. F necessary, update or install the lorry
‘The Android Testing Support Library classes are located under the androld.suppot.est package. There are also older
testing APIs in androi.test. You should use the support bares frst, when given a choice between the suppor lraries
‘andthe older API, as the support lrares help build and cistibute tests ina cleaner and more reliable fashion than
Airectly coding against the API tse
Setting up testing
Te prepare your project for testing in Android Studi, you need to
+ Organize your tests in a source set
‘+ Configure your project's gradle dependencies to include testing elated APIs
Andr
Stu
source sets
‘Source sets are a collection of related code in your project that are for diferent bull targets or otner“Tavors*of your app.
\When Android Studio creates your project, it creates the source sets for you:
‘+The main source set, for your app's code and resources.
‘+ The test source set, fr your app's local unt tests.
+The androldTest source set, for Android instrumented tests
‘Source sets appear in the Android Studio Android view under the package name for your app. The min source set
includes just the package name. The test and androidTest source sets have the package name followed by (test) or
(androidTest), respectivelyCsledicl] €p Project Files | @} Problems| <> © + | #~
Project
Caapp
= » Eimanifests
7) vy Diava
E)com.example.android.mytestapp
. © & MainActivity
3 » Elcom.example.android.mytestapp (androidTest)
2 y Elcom.example.android.mytestapp (test)
? (@ & ExampleUnitTest
Cares
6 © Gradle Scripts
‘These source sats correspond to folders in the sr directory for your project. For example, the files forthe test source set
are located in srctestjava,
Configure Gradle for test dependencies
To use tho uit testing APIs, you need to conigure the dependencies for your project. The default gral bul fle for your
project includes some ofthese dependencies by default, but you may need to add more depencencias for additional testing
{features such as matching or mocking frameworks.
In your app'stopevel build gradle file, speciy these libraries as dependencies, Nate thal the version numbers for these
Ioraries may have changed. If Android Studio reports a newer library, update the number to rflect the current version
copenseneses (
testcase “suntessunitee 22"
[After you ad dependencies to your bulé.gradle fle you may have to syne your project to continue. Click Syne Now in
Android Stuclo when prompted,
Configure a test runner
Atest runner isa library oF set of tools that enables testing to occur and the result to be printed to log. Your Android
project has access toa basic JUnit test runner as part ofthe JUnit APIs, The Android test support brary inchides a test
runner forinstrumented and Espresso tests, androisivatrunrer, which also supports Junt 3 and 4
“This chapter only demonsiates the default runner for unit tests. To set AndroidJUnitRunner as the default test runner in
your Gracle project, add te following dependency to your buld.radle file. There may already be dependences inthe
‘ofaullConig section. Ifs0, add tho tostinstrumentationRunner line to that section.anarosd ¢
)
Creating and running unit tests
Create your unit tests as a gener Java fle using the JUnit 4 APIs, and store tose tess in the test source set. Each
[Android Stucio project tamplats includes this source set and a sample Java test file called ExamplaUitTast.
Create a new test class
To create anew tet class file, adda Java fe tothe test source eet for your projec. Test clas files for unit esting are
‘ypicaly named for the class in your app that you ae testing, with “Test” appended. For example, if your have a class called
Calculator n your app, the class for your uni tests would be CalculaorTest.
To add a new test class fle, use these stops
1 Expand the java folder andthe folder for your apps test source set. The existing unit test class files are shown,
2, Right-click on the test source set folder and select New > Java Class,
3. Nam the fle and cick OK.
Write your tests
Use JUnit syntax and annotations to write your tests. For example, the tet class shown below includes the following
annotations
‘+ The @RunWith annotation incicates the test runner that should be used forthe tests in this class,
‘+ The @SmalTest annotation inaicates that ths isa small (and fastest.
‘+ The @Before annotation marks a method as being the setup forthe test
‘+ The @Test annotation marks a method as an actual test
For more information on JUnit Annotations, see the JUnit Reference documentation
enunusen(sunieacass)
punlie clats aleulatorrast (
teerere
public vord seep0) ¢
,
frost
bles vats adtacnanters() (
double resultadd = weslculateradi(24, 1)
assertthat(resultade, 1s(eauatTo(20))
The addTwoNumivers{) method isthe only actual test. The key pat ofa unittest the assertion, which is defined here by
the assertThat() method, Asserions are expressions that must evaluate and result in a value of rue forthe test to pass.
Unit 4 provides a numberof assertion methods, but assertThal)s the most flexible, as it allows for general-purpose
comparison methods called matchers. The Hamerest framework is commonly used for matchers("Hamerast” is an
‘anagram for matchers). Hamerest includes a large numberof comparison methods as wall as enabling you a write yourTesting your App
For more information on assertions, see the JUnit reference documentation for the Asser class. For more information on
the hamorest framework, see the Hamcrest Tutor
Note thatthe adaTwoNumbers() method in this example includes only one assertion. The genera ule fr uni tests is to
provide a separate test method for avery incvidual assertion, Grouping mare than one assertion ina a single method can
‘make your tests harder to debug if only ane assertion fails, and obscures the tests that do succeed,
Run your tests
Torun your local unit test, use these steps:
‘+ Toruna single test, right-click that tst method and select Run.
‘+ To lest all the methods ina test cass, right-click th test flo inthe project view and select Run,
‘+ To runalltosts ina directory, rightclick an the directory and select Run tests.
‘The project bulls, necessary, and the testing view appears atthe bottom ofthe screen. If all the tests you ran are
successful, the progress bar at the top ofthe viow tums groon. A slatus mossage inthe footer also reports “Tests Passed.”
>-esu Bs st eds
> » Caer ome iS ry Dror hin o.1.0 7250 Cotst/om jo +
“iia rece ines with est co © +
a =
a °
a a
WAM 21000 5K
Related Practical
‘The related exercises and practical documentation isin Actos Develoger Fundamentals Practical,
‘+ Testing Apps With Unit Tests
Learn More
‘+ Beet Practoes for Testing
++ Getting Started with Testing
‘* Bulling Local Unit Tests
‘+ JUnt 4 Home Page
+ JUnt 4 API Reference
‘* Mockito Home Page
‘Android Testing Support Testing Patterns (ideo)
‘Android Testing Codelab
‘Android Tools Protp: Test Size Annotations
‘The Benefis of Using assertThal over other Assert Methods in Unit Tests