Hands-on: Debugging an Android Application

Roll up your sleeves, start up the Android Emulator and debug your application line by line.

Debugging Strategy

Mobile application development has a lot of similarities with writing software for the desktop and for the web — what works there generally works in the mobile world as well. Write your code in a modular fashion, be mindful of not over-stretching resources such as memory and persistent storage, and of course remember to comment your code. Some day someone will need to update the code — and it just might be you! Where mobile application development and traditional development platforms begin to diverge in earnest is in the area of application testing and debugging. If you are just getting started with mobile application development, you will want to go in with your eyes open as it can take a little getting used to working with the available mobile tools. Fortunately for us, debugging Android applications is really a rather painless activity once you get a feel for the available tools and approach.

In this article we step through the process of configuring Eclipse to test your application on the Android Emulator. Once the application is up and running on the emulator, we take a look at the capabilities of the Dalvik Debug Monitoring Service (DDMS) and then move to setting breakpoints in Eclipse to follow our application, line by line.

Run Configurations

Eclipse presents a rich Java development experience to the Android developer. We previously looked at some of the development facilities of Eclipse with the Android Developer Tools (ADT) plugin. The ADT includes WYSIWIG user interface tools and the tools used to convert the resource layout files into the necessary ingredients to build an Android executable. In addition to the design- and compile-time tools, the ADT also includes functionality to assist us in testing and debugging our applications. Let’s have a look at those now.

Testing an application starts with creating a Run Configuration. Here is a step-by-step guide to creating a Run Configuration for our TicketResponder application.

Create a new Android Configuration. Highlight “Android Application” and then click on the “New” icon as seen in the image below.

We now have three tabs of information related to the testing of this application. In the first tab, we give our configuration a name. In the image below we see that I have chosen the name “Launch Config Name” (sorry, not very creative, I know…). Please feel free to use something more descriptive like “TicketResponder”. Next, select the Project by clicking on the Browse button. If you have multiple Android projects in your Eclipse workspace, you can choose the project you desire to test. Once the project has been selected, choose which Activity you would like to Launch upon start-up. Alternatively you can just leave the “Launch Default Activity” as the selected launch action.

Now that we have setup the project-specific settings, we need to configure the emulator aspect of the launch configuration. To do this we move to the “Target” tab where we an specify which emulator environment to launch. This means we need to have a compatible Android Virtual Device configuration available. In the image below you can see that we have a single AVD configured with a name of Google15. That is a name I gave it to let me know that it is using the Google APIs and is compatible with the 1.5 version of the SDK platform. In each release of the Android Developer Tools over the past year the options have changed a little so don’t be surprised if your environment doesn’t match these images 100%. Oh yeah, that is the other aspect of mobile development that I should mention — stuff moves — and quickly!

So what do you do if you don’t have an AVD available yet? You create one with the AVD Manager! Click on the AVD Manager button and a new dialog will launch showing both the available AVDs on your computer and a section where you can create a new AVD. Note in the image below that I’ve got the entries setup to create a new AVD named “MyAVD” which is based on the Google APIs and is using the HVGA-L (landscape) skin. We can also add a virtual SDCard to simulate removable storage in the Android Emulator. Clicking on the Create AVD button will create this AVD and allow us to select it for our testing purposes.

API versions

I want to make a quick comment regarding the platform version you choose. At present the TicketResponder application does not use the Google mapping APIs — so we could use an AVD based on the Android 1.5 platform. However if we were to add mapping capabilities, our application would not run properly. Therefore, I’ve chosen to go ahead and use the Google API platform right from the start because I anticipate adding some flavor of mapping to the application in an upcoming article. This is a common pitfall among newcomers to Android and I wanted to address it before you went ahead and added some cool functionality ahead of me and then wondered why it wouldn’t work on your emulator setup! Speaking of the emulator, we’re almost done configuring it, so let’s wrap that up and test our application.

Android Emulator

Note in the image below the Emulator launch parameters. The opportunity to testing a mobile applications on an emulator is a wonderful characteristic of a platform — anyone who has slogged through a project where every tiny feature had to be installed on the device can testify that that is now way to live! The emulator is perfect for testing application flow and logic, but it can sometimes lead you to an unhealthy dependence upon broad-band connectivity! To this end, the Android emulator provides some launch options where you can simulate more realistic wireless latency and speed conditions to see how your application behaves.

You can also choose to wipe out the persistent storage of the emulator upon every launch. In most cases, I don’t use this feature, however it is occasionally of some utility when you need to get back to a clean data state. OK, we’re almost done with setting up our Run Configuration. The last thing we want to do is on the third tab named “Common” as seen in the image below. We want to simply select the check-boxes next to Debug and Run. This puts this run configuration in the favorites menu, speeding things up for us a bit. Considering the fact that you will likely run your application dozens or hundreds of times before releasing it, you will want to take advantage of any time-saving convenience you can.

Now that we have our Run Configurations setup on the favorites menu, running our application is as simple as selecting our configuration from the favorites drop-down. And Eclipse remembers your most recent selection, so you can just click on the menu, without the drop-down selection for subsequent, consecutive launches of the same application.

Starting Up!

When you click on your Run Configuration from the favorites menu, you should see an instance of the Android Emulator launch. This may take a few moments, so be patient. You can watch along in the “Console” window in Eclipse to see progress messages as the kernel revs up. If you are having trouble getting the Android Emulator to start up for you, the best guidance is to review this console log to find any obvious error messages. There is a fair amount of plumbing involved in getting the emulator running properly behind the scenes so don’t be afraid to sift through this log — it is actually quite interesting. Well, perhaps not to everyone but it is to me.

If you are having difficulty getting the emulator to start through Eclipse, you might also try to run it from the command-line. The emulator is found in the tools directory of the Android SDK. For example, on my Windows laptop, the SDK is installed in c:\software\google\android-sdk-windows-1.5_r3. Here is a directory listing of the tools directory.

07/28/2009  01:07 PM    <DIR>          .
07/28/2009  01:07 PM    <DIR>          ..
06/30/2009  05:47 PM            43,684 acp.exe
06/30/2009  05:47 PM         2,258,137 adb.exe
06/30/2009  05:47 PM           106,496 AdbWinApi.dll
06/30/2009  05:47 PM             1,688 android.bat
06/30/2009  05:47 PM             1,391 apkbuilder.bat
06/30/2009  05:47 PM             1,564 ddms.bat
06/30/2009  05:47 PM           125,033 dmtracedump.exe
06/30/2009  05:47 PM             1,319 draw9patch.bat
06/30/2009  05:47 PM        10,368,783 emulator.exe
06/30/2009  05:47 PM           994,250 fastboot.exe
06/30/2009  05:47 PM             1,356 hierarchyviewer.bat
06/30/2009  05:47 PM            30,963 hprof-conv.exe
06/30/2009  05:47 PM    <DIR>          Jet
06/30/2009  05:47 PM    <DIR>          lib
06/30/2009  05:47 PM            29,498 mksdcard.exe
06/30/2009  05:31 PM           156,733 NOTICE.txt
06/30/2009  05:47 PM         1,648,366 sqlite3.exe
06/30/2009  05:47 PM             1,388 traceview.bat
              16 File(s)     15,770,649 bytes

Note the file mksdcard.exe — if your application testing requires the use of an SDCard, you will want to use this utility to create an SD-compatible file for use with the Android Emulator. Note also the sqlite3.exe file — this is useful for working with Android-compatible databases.


OK, so now our application is running, now what? Well, how would you like to peer into the running device? We can do just that with the Dalvik Debug Monitoring Service (DDMS). We view the DDMS by switching the Eclipse Perspective and choosing DDMS from the Window | Open Perspective menu. If DDMS is not visible, choose “Other”, which will bring up another window.

When the DDMS opens, take a moment to look around. Your display will vary depending on what applications are running and what files are present on your emulator or device. If you have a real device (development or rooted) connected, it will show up here as well. Note that it is also possible to have multiple Android Emulators running concurrently, which is a topic for another day! Clicking on the device in the “Devices” window will cause the Threads, Heap, and File Explorer windows to reflect the currently selected device/emulator’s running values. In the image below you can see that I have found our running application in the file system. User applications are found in the /data/app directory.

In addition to being able to navigate the file system we can also pull screen shots, push and pull files, view logs and much more. The DDMS is a rich environment and helpful tool – we’ll look into this more in a future article. But for now, let’s take a quick look at setting break-points in Eclipse to debug your Android application.

Line by Line

To debug your Android application, switch to the “Debug” Perspective. You can find this with the Window | Open Perspective | Debug menu option. This will display the source file in a window along with some other convenience windows including — variables, breakpoints, outline, and others. This environment can be customized to suit your tastes. Just a warning and a hint — if you find that you’ve hopelessly messed up the windows and cannot seem to get them back the way you prefer, just select the “Reset Perspective” menu under the Window menu. Been there, done that.

To set a break-point, just double-click in the left hand margin next to the line you would like code execution to stop — you should see a tiny blue circle indicating a break-point is present on that line. Double clicking again will remove the break-point. Next, run your application by choosing the Run Configuration you created earlier — but this time from the Debug Favorites menu! Let’s try this out

I have placed a break-point on the line that handles the case where an empty ticket number is entered.

We trigger this code by hitting the “Update Ticket” button in our application, but without having provided a value in the ticket number edit box:

Code is now stopped on the AlertDialog.Builder line — and we can do the usual debugging routine: check variable contents, single-step in or over this line, set additional break-points, etc. Note the “VCR” buttons at the top of the Debug window which permit easy navigation — you shouldn’t have to hunt for the right key-stroke.

At this point we’ve got our application up and running on the Android Emulator, we can watch the process in the DDMS and we can step through the code line by line! Now that we have a solid environment to build and test applications with, we can begin adding more features to our application.

Comments on "Hands-on: Debugging an Android Application"

I truly appreciate this post. I have been looking everywhere for this! Thank goodness I found it on Bing. You’ve made my day! Thank you again

Here is an excellent Blog You may Discover Intriguing that we encourage you to visit.

Check below, are some totally unrelated websites to ours, having said that, they may be most trustworthy sources that we use.

Very few web sites that come about to become in depth beneath, from our point of view are undoubtedly effectively really worth checking out.

We prefer to honor a lot of other web internet sites around the internet, even when they aren?t linked to us, by linking to them. Underneath are some webpages really worth checking out.

Every after in a when we decide on blogs that we read. Listed beneath are the newest web-sites that we opt for.

The time to study or take a look at the material or websites we’ve linked to below.

The time to read or visit the content or web pages we’ve linked to below.

Llevado a la seccion de Telefonia de dicho Corte Ingles,ya que mi mujer lo habia comprado alli, se hacen cargo del telefono,mandandolo al servicio tecnico de Samsung….esto lo hacen cuatro veces, viniendo el telefono NUNCA arreglado, es mas,la ultima vez que llego,fue delante justo del comercial y jefe de la seccion, que mostro su problema de reinicio…Dio la impresion que no me creian hasta que lo vieron ellos.

Empresa prestadora de Servicios Jurídicos Pre pagados con Excelente proyección profesional, requiere Abogado Especialista en Derecho Laboral Comercial con Experiencia mínima de 3 años en el área, con alta responsabilidad y ética, excelente presentación personal. Empresa vinculada en el sector salud, solicita técnicos sistemas que se encuentren en etapa productiva, con un salario del 75 sobre el smlv más prestaciones sociales, con disponibilidad de tiempo completo.

Excelente la pagina, escribo para decir que tengo una nevera no frost tecnico le puso el gas porque se llamo para eso ya que este se le habia acabado pero que do con el problema de que se congela en la parte de atras y cada dos tres dias hay que descongelarla y no se puede dejar para hacer cubos de hielo y no enfria nada en la parte solo se congela en la parte de atras ayudaaaaa gracias.

We like to honor lots of other web web-sites on the internet, even when they aren?t linked to us, by linking to them. Under are some webpages worth checking out.

Encuentra de forma rápida e intuitiva todo lo que tienes cerca y te interesa. Reparamos múltiples marcas y estamos capacitados para reparar la mayoría de los aparatos con la mayor garantía de la Comundiad de Madrid. Todos los logotipos y marcas mostradas en esta página web son propiedad de sus titulares y están protegidos por el copyright. Nosotros haremos el pedido al proveedor y le avisaremos cuando puede recoger el pedido cómodamente en nuestra tienda en Madrid.

We prefer to honor a lot of other web websites on the web, even if they aren?t linked to us, by linking to them. Below are some webpages worth checking out.

That could be the finish of this post. Here you will discover some internet sites that we feel you will value, just click the links.

Leave a Reply