Mock tests, Interview questions, Tutorials and Tech news
 
 
Home > Programming / tutorials > Android Activity Life cycle:LogCat and exception handling

Android Activity Life cycle:LogCat and exception handling

January 16th, 2011 Leave a comment Go to comments

In The last 2 posts of android development , we had talked about android development

Getting Started with Android Development
Building an android application

In this we will take you inside exception handling

LogCat and exception handling:

Once you have your “Test Activity” app running as we had shown in Getting Started with Android Development, 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 TestActivity application:

?

123

4

5

6

public void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.main);

Log.i(TAG,”On Create”); // LogCat message // TAG=”TestActivity”

}

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 “TestActivity” which will only display log messages tagged as “TestActivity”, 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:

?

1234 Log.i(“TestActivity”, “Hello LogCat!”); // LogCat messageString test = null;if (test.equals(“hello”)) Log.i(“TestActivity”, “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 “TestActivity” 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:

?

1234

5

6

7

8

9

10

11

12

13

14

Log.i(“TestActivity”, “Hello LogCat!”); // LogCat messagetry {    String test = null;    if (test.equals(“hello”))

Log.i(“TestActivity”, “The test string is hello”);

} catch (Exception e) {

// handle any errors

Log.e(“TestActivity”, “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.

Note : Please refer to the original article here http://www.androidza.co.za/beyond-hello-world-logcat-and-exception-handling/

Be Sociable, Share!
Categories: Programming / tutorials Tags:
  1. October 26th, 2011 at 07:07 | #1

    Yes Toby. Looks like the person got inspired from your article and used the same contents. Sorry about that. I will add a link to your article

  2. Toby Kurien
    October 25th, 2011 at 08:17 | #2

    Hey guys, you’ve blatantly stolen my article from here:
    http://www.androidza.co.za/beyond-hello-world-logcat-and-exception-handling/

    Please remove this content and link to my original article.

  3. July 13th, 2011 at 05:25 | #3

    You could also use http://www.Bugsense.com in order to get your android exceptions (it’s free, with analytics and realtime).

  4. eo
    June 29th, 2011 at 11:50 | #4

    hey thanks

  1. January 16th, 2011 at 22:35 | #1
  2. January 17th, 2011 at 22:22 | #2

Get Adobe Flash playerPlugin by wpburn.com wordpress themes