Debugging an Android Widget

While working on my Udacity Android Developer Nanodegree recently I ran into an issue with the widget that was required as a part of a course project design. The app being developed was a recipe app and part of the requirements was that it offered a widget to display the ingredients of a selected recipe. The app was developed using Android Studio and the built-in debugger and access to many different device emulators made the initial debug of the app and the widget straight forward. However, just prior to submitting my project for review I was doing some final testing, checking for as many edge cases as possible and I ran into an exception when the widget was added to the home screen.

The scenario causing the exception was the instantiation of the widget when the app was not running. This presented a big problem from the debugging perspective because in order to attach the debugger to the code some process that is a part of the code base needed to be running, a chicken and egg situation for sure!

After much Internet searching I finally found a solution that enabled me to debug the widget under this condition. The technique exploits the fact that when any part of a project is loaded and running on a device/emulator, the whole code base is available to be debugged. The trick was to get the project code loaded onto the device/emulator without starting the main app activity. Once one is aware of that requirement is fairly easy to image how to arrange this … create a new empty activity and set in as the startup activity in the project manifest. When the app is then run on the device/emulator it is possible to set breakpoints in the widget startup code and when the widget is instantiated the breakpoints will be triggered and allow the controlled debug of the exception.

In my case the widget was making assumptions about some data that were only valid when the main app was running. Once identified the solution was easy and the original main activity could be re-enabled as the startup activity in the app manifest.


Tagged with: , ,