Debugging errors in Android

Android has a great framework to work in. However, it is in its infancy and debugging my code has been a very big problem for me. Whenever something goes wrong in the code, I always get “source not found” error. It doesn’t tell me I have a nullPointer exception , or string is incomplete.  No matter what’s wrong with the code, I always get “source not found” error. The reason that happens is Android doesn’t pack the source along with the application it sends to the emulator (maybe they should do that for a debugging run). After searching the net for a while, I came across this solution – wrap your code in a try and catch block and then log the exception to console. Here is an example :

public class SomeClass extends ListActivity {
	private AlertDB db ;
	private static final int ALERT_ADD = 100;

	@Override
	public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	//setContentView(R.layout.alert_list);
	try {
		db = new AlertDB(this);
		Cursor c = db.fetchAllAlerts();
	} catch (Exception e) {
		Log.e("ERROR", "ERROR IN CODE:"+e.toString());
	}
}

Doing that will display a neat little line in your logcat window (look at the screenshots at the bottom). And, instead of getting the annoying “source not found” error. You will know what the actual error is. In Android, you can log three types of events – information, warning and error. Information is just verbose text being written out to the log.  I don’t need to explain warning and errors.

For logging information you can use :

Log.i(TAG, message);

For logging warnings you can use :

Log.w(TAG, message);

I have already shown how to log errors in the code above.

Click to enlarge
Click to enlarge
Click to enlarge
Click to enlarge

Comments

2 responses to “Debugging errors in Android”

  1. Kevin Prichard Avatar
    Kevin Prichard

    Good post, useful info. Have you found a way to debug Android source itself?

  2. moazzam Avatar

    I haven’t had a chance to mess with the Android’s source much but you *should* be able to do it by logging exceptions.

Leave a Reply

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