This practical codelab is part of Unit 1: Get started in the Android Developer Fundamentals (Version 2) course. You will get the most value out of this course if you work through the codelabs in sequence:
In previous practicals you used the
Log class to print information to the system log, which appears in the Logcat pane in Android Studio when your app runs. Adding logging statements to your app is one way to find errors and improve your app's operation. Another way is to use the debugger built into Android Studio.
In this practical you learn how to debug your app in an emulator and on the device, set and view breakpoints, step through your code, and examine variables.
You should be able to:
The SimpleCalc app has two
EditText elements and four
Button elements. When you enter two numbers and click a
Button, the app performs the calculation for that
Button and displays the result.
For this practical you won't build the SimpleCalc app yourself. The complete project is available at SimpleCalc. In this task you open the SimpleCalc project in Android Studio and explore some of the app's key features.
Examine the layout XML code and design and note the following:
EditTextelements for the input, four
Buttonelements for the calculations, and one
TextViewto display the result.
Buttonhas its own
android:onClickclick handler (
OnSub, and so on.)
TextViewfor the result does not have any text in it by default.
EditTextelements have the
android:inputTypeattribute and the value
"numberDecimal". This attribute indicates that the
EditTextaccepts only numbers as input. The keyboard that appears on-screen will only contain numbers. You will learn more about input types for
EditTextelements in a later practical.
MainActivityclass, this project also includes a utility
enum, and that all of the operation methods are
Note the following:
android:onClickclick handlers call the private
compute()method, with the operation name as one of the values from the
compute()method calls the
getOperand()(which in turn calls
getOperandText()) to retrieve the number values from the
compute()method then uses a
switchon the operand name to call the appropriate method in the
Calculatorclass perform the actual arithmetic and return a value.
compute()method updates the
TextViewwith the result of the calculation.
Run the app and follow these steps:
EditTextelements empty, and try any calculation.
If one or both of the
EditText elements in SimpleCalc are empty, the app reports an exception, as shown in the figure below, and the system log displays the state of the execution stack at the time the app produced the error. The stack trace usually provides important information about why an error occurred.
In this task you'll get an introduction to the debugger in Android Studio, and learn how to set a breakpoint and run your app in debug mode.
Android Studio builds and runs your app on the emulator or on the device. Debugging is the same in either case. While Android Studio is initializing the debugger, you may see a message that says "Waiting for debugger" on the device before you can use your app.
A breakpoint is a 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 errors. You can set a breakpoint on any executable line of code.
compute()method (the line just after the
As an alternative, you can choose Run > Toggle Line Breakpoint or press Control-F8 (Command-F8 on a Mac) to set or clear a breakpoint at a line.
If you click a breakpoint by mistake, you can undo it by clicking the breakpoint. If you clicked a line of code that is not executable, the red dot includes an "x" and a warning appears that the line of code is not executable.
EditTextelements and click one of the calculate
The execution of your app stops when it reaches the breakpoint you set, and the debugger shows the current state of your app at that breakpoint as shown in the figure below.
The figure above shows the Debug pane with the Debugger and Console tabs. The Debugger tab is selected, showing the Debugger pane with the following features:
Click the Threads tab to replace the Frames pane with the Threads pane. Your app is currently running in the main thread, and that the app is executing the
compute() method in
operator(the operator name from
Calculator.Operatorthat the method was called from), as well as the global variables for the
EditTextelements and the
TextView. Each variable in this pane has an expand icon to expand the list of object properties for the variable. Try expanding a variable to explore its properties.
Resume your app's execution by choosing Run > Resume Program, or click the Resume icon on the left side of the debugger window.
The SimpleCalc app continues running, and you can interact with the app until the next time the code execution arrives at the breakpoint.
If your app is already running on a device or emulator, and you decide you want to debug that app, you can switch an already running app to debug mode.
The Debug pane appears with the Debugger pane open, and you can now debug your app as if you had started it in debug mode.
In this task we'll explore the various features in the Android Studio debugger, including executing your app line by line, working with breakpoints, and examining variables.
After a breakpoint, you can use the debugger to execute each line of code in your app one at a time, and examine the state of variables as the app runs.
EditTextelements, and click the Add button.
Your app's execution stops at the breakpoint that you set earlier, and the Debugger pane shows the current state of the app. The current line is highlighted in your code.
The debugger executes the current line in the
compute() method (where the breakpoint is, the assignment for
operandOne), and the highlight moves to the next line in the code (the assignment for
operandTwo). The Variables pane updates to reflect the new execution state, and the current values of variables also appear after each line of your source code in italics.
You can also use Run > Step Over, or press F8, to step over your code.
operandTwo), click the Step Into icon.
Step Into jumps into the execution of a method call in the current line (compared to just executing that method and remaining on the same line). In this case, because that assignment includes a call to
getOperand(), the debugger scrolls the
MainActivity code to that method definition.
When you step into a method, the Frames pane updates to indicate the new frame in the call stack (here,
getOperand()), and the Variables pane shows the available variables in the new method scope. You can click any of the lines in the Frames pane to see the point in the previous stack frame where the method was invoked.
You can also use Run > Step Into, or F7, to step into a method.
getOperand(). Note that when the method completes the debugger returns you to the point where you first stepped into the method, and all the panels update to show the new information.
The debugger executes the appropriate method defined in the
Calculator class, opens the
Calculator.java file, and scrolls to the execution point in that class. Again, the various panes update to reflect the new state.
MainActivity. You can then continue debugging the
compute()method from where you left off.
You can also use Run > Step Out or press Shift-F8 to step out of a method execution.
Use breakpoints to indicate where in your code you want to interrupt your app's execution to debug that portion of that app.
(operandOne == 42)||(operandTwo == 42)
This second breakpoint is a conditional breakpoint. The execution of your app will only stop at this breakpoint if the test in the condition is true. In this case, the expression is only true if one or the other operands you entered is 42. You can enter any Java expression as a condition as long as it returns a
EditTextand click any
Button. Click Resume to resume execution after the first breakpoint. Observe that the second breakpoint at the
switchstatement—the conditional breakpoint—halts execution because the condition was met.
compute()and uncheck Enabled. Click Done. Observe that the breakpoint icon now has a green dot with a red border.
Disabling a breakpoint enables you to temporarily "mute" that breakpoint without actually removing it from your code. If you remove a breakpoint altogether you also lose any conditions you created for that breakpoint, so disabling it is often a better choice.
You can also mute all breakpoints in your app at once with the Mute Breakpoints icon.
The Breakpoints window enables you to see all the breakpoints in your app, enable or disable individual breakpoints, and add additional features of breakpoints including conditions, dependencies on other breakpoints, and logging.
To close the Breakpoints window, click Done.
The Android Studio debugger lets you examine the state of the variables in your app as that app runs.
The first breakpoint in
compute() is still muted. Execution stops at the second breakpoint (the conditional breakpoint at the
switch statement), and the debugger appears.
operandTwovariables have the values you entered into the app.
thisvariable is a
MainActivityobject. Click the expand icon to see a list of member variables of that object. Click the expand icon again to close the list.
operandOneto 10 and press Return.
operandTwoto 10 in the same way and press Return.
Buttonin Step 2, the result in the app is now 20.
EditTextelements. (Their values were changed only in the debugger.) Click the Add button. Execution halts at the breakpoint again.
The Evaluate Code Fragment window appears. Use it to explore the state of variables and objects in your app, including calling methods on those objects. You can enter any code into this window.
EditTextis the string
"Type Operand 1", as was originally defined in the XML for that
The result you get from evaluating an expression is based on the app's current state. Depending on the values of the variables in your app at the time you evaluate expressions, you may get different results.
Note also that if you use Evaluate Expression to change the values of variables or object properties, you change the running state of the app.
Challenge: At the end of Task 1, you tried running the SimpleCalc app with no value in one of the
EditText elements, resulting in an error. Use the debugger to step through the execution of the code and determine precisely why this error occurs. Fix the bug that causes this error.
The related concept documentation is in 3.1: The Android Studio debugger.
Android Studio documentation:
This section lists possible homework assignments for students who are working through this codelab as part of a course led by an instructor. It's up to the instructor to do the following:
Instructors can use these suggestions as little or as much as they want, and should feel free to assign any other homework they feel is appropriate.
If you're working through this codelab on your own, feel free to use these homework assignments to test your knowledge.
Open the SimpleCalc app.
MainActivity, place a breakpoint on the first line of the
Run the SimpleCalc app without the debugger. Leave one or both of the
EditText elements empty, and try any calculation. Why did the error occur?
java.lang.NumberFormatException: empty String
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED
Which function do you perform in the Debug pane in order to execute the current line where the breakpoint is, and then stop at the next line in the code? Choose one:
Which function do you perform in the Debug pane in order to jump to the execution of a method call from the current line where the breakpoint is? Choose one:
No app to submit for this homework assignment.
To find the next practical codelab in the Android Developer Fundamentals (V2) course, see Codelabs for Android Developer Fundamentals (V2).
For an overview of the course, including links to the concept chapters, apps, and slides, see Android Developer Fundamentals (Version 2).