[6] Android Debugging Your App - mariamaged/Java-Android-Kotlin GitHub Wiki
Android - Debugging Your App
Sometimes, your app will crash when testing it.
1. Setting Breakpoints
- For lines containing lamda expressions, you will get a drop-down menu of options for what the breakpoint should effect:
- Set the breakpoint for the initial code on the line ("Line").
- Set the breakpoint to trigger when the lamda expression is executed ("{ updateButton() }").
- Both("All").
2. Launching the Debugger
- This behaves a lot like when you normally run the app.
- However, the app will run more slowly, and when the breakpoint is reached, your IDE window will open a Debug tool that shows you what is going on.
- However, the app will run more slowly, and when the breakpoint is reached, your IDE window will open a Debug tool that shows you what is going on.
3. Examining Objects
- The middle of the Debug tool shows a "Variables" list.
- This will contain local variables, field/properties of the current object, and other values that your code might be referencing.
Simple types
, like the Long startTimeMs, just show their value.More complex types
, like AppCompatButton will show their type and can be explored in turn using the gray triangle to expand the object tree.
4. Stepping Through the Code
On the Top
- From left to right, these are:
- Execute this statement and move into the next one.
- Step into the function being called in this statement, if it is not an Android SDK function.
- Step into the function being called in this statement, even if it is an Android SDK function.
- Execute far enough to exit the function that we are in and then stop.
On the Left
- Of particular note:
- The top-most button (green triangle) will start executing code until the next
breakpoint
orcrash
. - The red square terminates your process.
- The fourth button (two-overlapping red dots) brings up a dialog box showing all of your breakpoints.
- The top-most button (green triangle) will start executing code until the next
5. Where Did it Go Wrong?
Kotlin
Java
- This code compiles, because setText() on a Button has a variant that accepts an Int as a parameter.
We are passing an Int that represents the number of seconds.
- As it turns out, setText(Int) does not show that Int value as text in the Button.
- Instead, Android is expecting that to be a
reference
to astring resource
, such as R.string.elapsed.
- Instead, Android is expecting that to be a
Those R values are all Integers, and so many functions in the Android SDK that accept an Int are expecting a resource ID, not some arbitrary value as we are providing.
In particular, if you get crash with an android.content.res.Resouces$NotFoundException, there is a good chance you are passing in a value to a function that is not a valid resource ID.
Solution
- Convert the numeric value to a String.