- Prerequisites
- Using LogCat
- Seeing a Common Mistake
- Testing Views
- Tracing Code
Tracing Code
The next problem, and our last, involves tracing code to figure out what the problem might be. Now that the second screen properly displays both the EditText and the Button controls above the soft keyboard, enter some text and click the Click When Done button.
Another crash? Yep! This time, though, you'll find that the button handler is being called, but LogCat shows a NullPointerException:
03-02 12:24:37.585: ERROR/AndroidRuntime(5116): Caused by: java.lang.NullPointerException 03-02 12:24:37.585: ERROR/AndroidRuntime(5116): at com.mamlambo.articles.bugged.OtherActivity.doToastAndExit(OtherActivity.java:18)
To debug this code, let's put a breakpoint in the first line of the doToastAndExit() method. To do this, take the following steps:
- Within Eclipse, switch to the Debug perspective and open the source file where the error is occurring (if it isn't opened already by default).
- Double-click in the margin to the left of the line you want the breakpoint on (Figure 8). The little blue dot indicates a breakpoint.
- Run the application again. When it reaches the breakpoint, your Eclipse window should look similar to Figure 9.
- On the first line, everything looks good. Click the Step Over button (highlighted on the left in Figure 9).
- Now, in the Variables pane (highlighted on the right in Figure 9) you'll see the editText value listed. It's null! Whoops.
- If you click Step Over again, you'll notice that the thread suspends and an exception is show in the Debug area (just below the highlighted Step Over button in Figure 9).
Figure 8 A breakpoint in Eclipse, highlighted
Figure 9 The variable values in Eclipse debugging perspective, shown highlighted on the right. The Step Over button is also highlighted.
What happened? Look at the findViewById() line—everything looks fine on the surface. But is it? The identifier looks fine, right? Double-check the value in the other.xml layout. Aha! It's supposed to be R.id.textField. Easy mistake, easy fix.
Change the value, run the application again, and the debugger will once again stop at the breakpoint. This time, step over and you'll find that the editText variable is no longer null. Hurray!
Conclusion
You have seen a variety of different kinds of bugs in this simple application. You have seen them appear in a variety of different ways and have learned a few tricks on how to spot them, locate them, and even fix them. The skill of debugging is critical to creating quality, stable products. There are literally hundreds of different ways bugs can manifest themselves. Being comfortable with the tools that help debugging will speed up the process tremendously and lead to better applications, happier users, and higher profits.