Monday, 6 August 2012

How to debug the Android mobile application with LogCat

When developing and testing an Android mobile application you can get a message like this:

The dialog window announces that the application has crashed, mainly because a runtime exceptions or error. Reasons for this situations are multiple and depends entirely on what you have done in the Android project. So, we now that something is wrong, but we have a a question:
How to find out what is the problem that forced the Android application to stop unexpectedly

Java programmers, that use Eclipse, know that if the application generates a runtime exception, they will get the exception details in the console window.

When developing Android applications in Eclipse the runtime exceptions messages are NOT displayed in the console window. Instead, the Android SDK comes with a tool, called LogCat, that logs all the platform messages.
How to open LogCat window

In Eclipse you can view the LogCat window by selecting Window -> Show View -> Other… and choosing LogCat from the Android category:
Open the Android LogCat View in EclipseOpen the Android LogCat View in Eclipse
The LogCat view displays logs generated by the Android emulator and by the mobile application:
LogCat View window in EclipseLogCat View window in Eclipse
Also, using the LogCat top toolbar you can filter logs based on their Tag, pid or Log Level (Error, Warning, Info, Debug, Verbose) or you can define your own custom filter.
LogCat Custom Filter EditorLogCat Custom Filter Editor

How to display messages in the LogCat window from code

A simple debugging technique is to display your own messages in the log window. For Java applications, this is done by printing messages in the console window using System.out.println(String message) method.
For Android projects, there is a better solution. The Log class has some static methods used to print messages in the system log which is displayed by LogCat view. Each method prints a message with a predefined log level:
        Log.e("MyTag", "Error message with my own tag");
        Log.w("dalvikvm", "VM Warning message");
        Log.d("MyTag", "Debug message");
        Log.i("MainActivity","Information message");
        Log.v("MyTag", "Verbose message");
        Log.wtf("WTF", "What a Terrible Failure");
The methods have multiple signatures. The previous example shows only the (String Tag, String Message) one. For tags is recommended to use your own tags or the class name. This will allow you to filter them easily.

No comments:

Post a Comment