LogCat is the most useful tool for debugging most issues with Android applications.
The first code defect we're going to explore will be solvable by just reading the output of LogCat while running the application. You can discover the problem by following these steps:
- Make sure the manifest file setting has the debuggable flag set to true.
- Launch the application with a debug configuration.
- Click the Launch Other Screen button (Figure 2).
- Observe the apparent crash (Figure 3).
Figure 2 Launch Other Screen button
Figure 3 A typical crash dialog with the Force Close button
Oops! What went wrong? Find out by switching to the Debug perspective in Eclipse. Then look at the LogCat output (Figure 4). If it's not showing already, you may need to go to Window, Show View, Other..., Android, then choose LogCat (Figure 5).
Figure 4 The LogCat output showing the exception in red
Figure 5 The Eclipse view chooser showing the LogCat selection highlighted
You should see, somewhere near the bottom of the LogCat output, an error line (usually in red) that looks like the following:
03-01 17:57:23.000: ERROR/AndroidRuntime(23308): java.lang.IllegalStateException: Could not find a method doShowOtherScreen(View) in the activity class com.mamlambo.articles.bugged.BuggyActivity for onClick handler on view class android.widget.Button with id 'mainButton'
Reading through the error, you might be able to guess that either the method isn't implemented or the method is misnamed. Review the code in BuggyActivity.java. Indeed, the method is actually called doShowSecondScreen(), not doShowOtherMethod(). You can fix this bug in two ways: either by changing the onClick attribute value for the Button in the XML resource file or by changing the name of the method within the Activity class. Either works and solves this problem.