Display a stack trace in the android debugger

I’ve found that when developing an application for android, it is not obvious how to display a stack trace in the debugger in order to assist with finding the cause of a problem. If you don’t catch the exception, the stack trace will display OK. However often you want to catch the exception, but when debugging you want to find out what caused it by logging it to the debugger.

In normal java, you might use e.printStackTrace, but this won’t work without the use of log redirecting in the adb as it is normally sent to /dev/null

I’ve written a small utility class to do this:

[code lang=”java”]
package com.example;

import android.util.Log;

/**
* A class to display a traditional Java stack trace in the android debugger
*
* @author Stuart Lewis (stuart@stuartlewis.com)
*/
public class StackTraceLogger {

/**
* Display a stack trace
*
* @param e The Exception
* @param tag The tag to use in the debugger
*/
public static void getStackTraceString(Exception e, String tag) {
Log.e(tag, e.toString());
for (StackTraceElement ste : e.getStackTrace()) {
Log.e(tag, ste.toString());
}
}
}
[/code]

To make use of this, in your catch use:

StackTraceLogger.getStackTraceString(e, TAG);

(where ‘e’ is the Exception, and TAG is your logging TAG). I hope this is useful.mobile java games

2 thoughts on “Display a stack trace in the android debugger

Leave a Reply

Your email address will not be published. Required fields are marked *