Android Cross-Device Optimization: Don’t Shoot Yourself in the Foot

I am sure everyone who ever developed for Android at some point has had the problem that views returned by “findViewById()” were null.

And yes, sometimes it has to do with eclipse which doesn’t detect changes when it is supposed to or other bugs of the development environment.

Nevertheless this can also be, like in 99,5% of all cases, your own fault. Also in my case – shooting yourself in the foot so to say.

I had decided I wanted to deploy directly on-device instead of the emulator, somehow the perceived waiting time is shorter for the apk to upload and install – a HTC Wildfire. This is a device with a small screen, so my layouts wouldn’t allow to sensibly interact with the app. I thought I would have to optimize anyway sooner or later, so I wrapped a scroll view around the most important layouts , placed the xmls into the layout-small folder and happy I was.

A week later, tons of code later, and after also collaboratively working with a colleague on the project, whenever I deployed to the HTC Wildfire my app would crash because of a null pointer exception. findViewById() was returning null. It was crashing only on the Wildfire, all other test devices were running fine.

For about three hours I kept asking myself: WHY?! There was something very awkward happening: when checking the child views in my main view with the debugger it said they were two TextViews and one Button. TextViews?! No, those are ImageViews I kept saying to myself. Weird…

And then suddenly, after also taking another pair of eyes on board for checking, alarm bells rang. This colleague of mine had modified the layout of a certain view, but only the “global” layout. Nevertheless there still was the small layout, which still contained TextViews instead of ImageViews and about which we totally had forgotten.
As the HTC Wildifre has a small screen, it would always return a TextView with the id “title”, while I was expecting an ImageView in my code.
I had totally forgotten about the small layouts.

Lesson learned: first get the app running and use the same layout for all screen sizes. Only after completely being finished start modifying anything that has to do with layouts.

Or take lecithin.