You’ve downloaded and installed the Android SDK, and followed the Hello World tutorial. Great! But what next? Before you begin to explore Android, you will need to be able to get information from your app and deal with errors. In this article, I will discuss the LogCat Android tool, and how to handle exceptions in your app. I will also give you some tips on avoiding the dreaded “Force close” dialog.
Once you have your “Hello World” app running (as per the tutorial), you can start learning about handling errors and getting debug information. While this may not sound like the sexiest thing to tackle next, this will save you a lot of hair-pulling as you will be presented with errors in a clear and meaningful way. Then you can bring on the sexiness!
If you are an experienced Java developer, you may be tempted to add some System.out.println() calls to do some exploratory programming. Fortunately, Android provides an easier and more structured way to get information from your app. To begin, let’s add a log message to your Hello World application:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i("HelloWorld", "Hello LogCat!"); // LogCat message
}
After entering the line of code, press Ctrl+Shift+O (organise imports) to import the android.util.Log class. The call to Log.i() creates an info log message. The first parameter is a tag, typically the name of your app, which you can use later to filter out specific log messages. The second parameter is the message to log.
To view the message, you will need to open the LogCat view in Eclipse. Click Window > Show View > Other > Android > LogCat > OK. Once open, you can run the app and watch the view. You will see a lot of messages from various parts of the Android system (OS and apps). Your message will come out in there somewhere! To make it easier to see just your message, click the + sign on the top right of the LogCat view, then fill in the dialog as follows, then click OK:
This will create a new tab in your LogCat view titled “HelloWorld” which will only display log messages tagged as “HelloWorld”, and when messages appear in this tab while it is unfocused, it will display a count of unread messages in the tab title. Handy!
Log messages can be one of several types: verbose (V), debug (D), info (I), warning (W), or error (E). You can click the corresponding letter in the top bar of the LogCat view to filter by that type of message or above. These are in increasing order of importance, so if you choose to see debug and above, you will also see info, warning, and error messages. Similarly, the Log class has methods for each type of message, e.g. Log.d() for debug.
Right, so you now have an easy way of displaying information from your application without having to worry about adding breakpoints and inspecting variables. Now let’s look at handling errors. To see how an error is naturally handled in Android, let’s create one in our app:
Log.i("HelloWorld", "Hello LogCat!"); // LogCat message
String test = null;
if (test.equals("hello")) Log.i("HelloWorld", "The test string is hello");
Eclipse will actually warn you about the impending doom, but since we’re too clever for that, let’s go ahead and run our app anyway. Suddenly, we are faced with the infamous “Force close” dialog:
At this point, it will be useful to know that there are two main reasons for a Force Close dialog: an unhandled exception (like this one), or an unresponsive app (perhaps stuck in an infinite loop or using too much CPU for too long). What went wrong? Well, our “HelloWorld” LogCat tab shows nothing, but the “Log” tab shows an error with a stack trace. Helpful, but that might get lost in the sea of log messages, so let’s add some error handling to our app:
Log.i("HelloWorld", "Hello LogCat!"); // LogCat message
try {
String test = null;
if (test.equals("hello")) Log.i("HelloWorld", "The test string is hello");
} catch (Exception e) {
// handle any errors
Log.e("HelloWorld", "Error in activity", e); // log the error
// Also let the user know something went wrong
Toast.makeText(
getApplicationContext(),
e.getClass().getName() + " " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
The try-catch block of code is standard Java exception handling. We log the error to LogCat in the catch block, and also display a Toast message to the user to show that there was an error. Now, when you run the app, you will see a notification come up about a NullPointerException, alerting you that something went wrong. This prompts you to look at your LogCat output, where the spilled guts of an exception are awaiting your postmortem. Since we have consumed the exception, no Force Close dialog appears. I recommend surrounding the entire code block in the onCreate() method with a try-catch block like this to avoid Force Closes entirely. For more complex applications, there will be several places where you will need to surround your code with try-catch blocks.
In summary, Android provides an easy way to log messages to a “console” (which in this case is LogCat). It is important to handle all exceptions thrown by your app (including RuntimeExceptions) to avoid Force Close dialogs. A good way to do this is to surround all executing code with a try-catch block, tag your messages and errors, log them to LogCat, and also present the user with a message about the error (using a Toast). Once you have this base covered, you can begin to code more freely and you will spend a lot less time tracking down errors and Force Closes.
This article was written by Toby Kurien, an Electronics Engineer with over 15 years of programming experience. Specializing in Java, Web technologies, and Android development, he lives his passion through creating applications and writing articles. Follow him on Twitter: @tobykurien
[...] Link: http://www.androidza.co.za/beyond-hello-world-logcat-and-exception-handling/ This entry was posted in Code Snippets. Bookmark the permalink. ← How to solve Must Override a Superclass Method Error [...]
tried to catch forced error by clicking a button to load another activity,,, did not work