Debugging Using Log.d and LogCat
In Chapter: Testing
Author: Rachee Singh (email@example.com) 'racheesingh'
Many a times even though the Java code compiles without error, running the application crashes giving a 'Force Close' (or similar) error message.
Debugging the code using Log Cat messages is a useful technique that a developer must be equipped with in such scenarios.
Those familiar with Java programming have probably used System.out.println statements while debugging their code. Similarly, debugging an Android application can be facilitated by the use of using the Log.d method. This helps print necessary values and messages in the Log Cat window.
Start with the import of the Log class:
Then, insert this line in the code at places where you wish to check the status of the application:
Log.d("Testing", "Checkpoint 1");
'Testing' is the Tag (which appears under the Tag column of Log Cat. 'Checkpoint 1'is the message (which appears in the Message Column of Log Cat). Log.d takes these 2 arguments. Corresponding to these, an appropriate message is displayed in the Log Cat. So if you have inserted this as a check point and you get the message displayed in Log Cat implies that the code works fine till that point.
The Log.d method does not accept variable arguments, so if you wish to format more than one item, use String concatenation or String.format (but omit the trailing %n):
Log.d("Testing", String.format("x0 = %5.2f, x1=%5.2f", x0, x1));