Category Archives: Android

A good programming regime

Sometimes a good regime creates a friendly environment for development.

By this I mean that rules forced in an operating system for the programmers should make it obvious how to code and how not to code. Apple for instance set very clear rules on running applications in the background (no applications in the background!), but also gave developers innovative push notifications. Android often follows with those innovations in the design of the Android API, but still leaves a lot of open space for doing things in the wrong way. The once famous quote by Magnus Lycka “It seems to me that Java is designed to make it difficult for programmers to write bad code, while Python is designed to make it easy to write good code.” is turning away from the former language even more, once Java became an interface for programming a wide area of system services and applications in Android.

I’ve met many people puzzled by the way android Activities work, especially when it comes to construction, destruction, and even things as simple as rotation (that involves destruction and re-construction of these objects). The simple answer is: never expect your activities to be there, like “Nobody expects the Spanish inquisition” in Monty Python’s sketches.

* If you’re an advanced Android developer, I’ll save you reading about the Activities, so click through to go to the juicy part of this article

While developers can decide how activities are launched in tasks, their construction and destruction is managed by system and they might be often left in one of the intermediate states, where they are not visible or probably about to shut down (see more about it in the Android Developers documentation).

The example is when we receive the phone call while browsing the application, the phone app comes to the foreground, and depending on the memory conditions, the application might even be shut down in the background (although it doesn’t have to). When we hang up the call, we expect to come back to the application without losing any introduced data. This data is often not in any permanent storage, but still in the UI (UI components like edit boxes, and additionally member variables). If not saved properly in the onSaveInstanceState() and restored in onCreate(savedInstanceState) or onNewIntent(savedInstanceState), these temporary changes might disappear.

As I mentioned previously, rotating the screen has the same effect on the Activities life-cycle, like if it was kicked out because of the lack of memory. It goes down all the way to the onDestroy() and gets recreated again. Developers often prevent it by allowing only vertical orientation of the application or even creating static member fields in the activity. This covers only half of the problem, and it’s more of a hack than the permanent solution. Member variables should be serialized using the Parcelable interface when activity requests that.

There are some objects that can’t be treated that way, i.e. background tasks. It’s a bad practice to re-instantiate the task when the activity got re-created. Just imagine fetching a large image file multiple times. There are two solutions for this problem. One is using the retainNonConfigurationInstance() request from the Activity, which returns the object that shall not be destroyed while activity is about to be recreated (although this approach has been deprecated in favour of the new ActivityFragment architecture). Another solution is to use Service to maintain long-running tasks in the background.

Well, all this information above could be surprising for the Android newbie. But there is another case of writing a quick but problematic one-line code that caught my eye recently.

Android doesn’t help developers handle remote image content easily. It requires quite a lot of code to transparently load images from either URL or the local content provider or the file stored somewhere on the file system. It would be nice yet if it was cached in the memory so we don’t have to reload it from either source each time. And the cache could have a limit depending on the device capabilities. And the CPU load should be optimised to let the more important content appear on the screen first. We’ve seen it all work somewhere, whether it’s a browser app, Gmail or twitter. Images are loaded smoothly while we browse the content.

Koushik Dutta created a great library for caching images from remote sources (whether they’re on the internet or just somewhere behind the content:// provider) and made it very flexible, so one can make it work right away with a very little effort but also use it in a bit more complex way. At the same time, the example provided with the app shows a very improper use of it’s own library. The activity fetches a JSON feed of images from Google, using the phrase provided by the user. Then it passes a list of URLs to the adapter and starts loading them.

    //in the http thread
    // add the results to the adapter
    runOnUiThread(new Runnable() {
        public void run() {
            for (String url: urls) {

    //in the adapter
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView iv;
        if (convertView == null)
            convertView = iv = new ImageView(UrlImageViewHelperSample.this);
            iv = (ImageView)convertView;

        // yep, that's it. it handles the downloading and showing an interstitial image automagically.
        UrlImageViewHelper.setUrlDrawable(iv, getItem(position), R.drawable.loading);

        return iv;

Right, this magically (almost) works, because adding each element to the list causes an obscure notifyDataSetChanged() call in the adapter and all list elements get redrawn. Some images might not get drawn in the right place though, but it will be hard to see in such a long list which we will be scrolling up and down, until all images are loaded…

Why is that? Adapters recycle list view entries as long as it’s possible (see convertView in the getView method), so the reference to the imageView will be the same across all the list. If we try to load images in all the entries, we will initialize the downloading in the right place, but when the result arrives ready to draw, only the last element in the list will be updated. Other list entries are only “dead” copies of the convertView (probably drawn to the canvas only once).

What would the solution be? Well there is one, already in the library. The method setUrlDrawable is overloaded with a bunch of different arguments. The one would be:

public static void setUrlDrawable(final ImageView imageView, final String url, final int defaultResource, final UrlImageViewCallback callback);

with the imageView set to null and callback set to the calling activity that would implement the onLoaded method with calling mAdapter.notifyDataSetChanged();

But remember about the activity construction and destruction, huh? What will happen to the orphaned tasks when we recreate the activity? How do we re-attach the observer to the tasks when needed?

I’ve created my own library that fetches images from the internet and content providers, and there I propose how to use it with the activities in the example. It forces the right coding style for refreshing the on-screen content by using the observer/callback pattern instead of holding the references to the views that might get invalidated with other data in the meantime. Please take look at the library and use it. And tell your fellow programmers to try it too. I welcome all comments. There’s surely room for improvement, but it might surprise you nicely with it’s functionality. And I hope the way it is designed helps understanding how it works.

I would also prefer the android Lint to help developers design code in the way it is more error-proof in the areas of object instance management. This part that is likely forgotten by developers with non-C experience (hello GarbageCollector). Although completely correct, this kind of code gives me a bit of a headache:

    search.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        // background the search call!
        Thread thread = new Thread() {
            public void run() {
                try {
                    // clear existing results
                    runOnUiThread(new Runnable() {
                        public void run() {

But when used in a recursive call becomes a really big pain, as mentioned above. It is cool to create instances on the spot, but putting extra effort to keep track of them has actually more value.

Other than that, Java is a really cool language (especially in Android). One thing I learned at the beginning of my experience with Android programming was: when there’s a problem, there must be some solution. This comic illustrates it quite well.

(with the courtesy of AndroidPolice)

PD. Anyway, thanks to Koushik Dutta for creating a really great piece of code. I don’t try minimise it’s value. It is a very useful library, although I got to know about it very recently, so I created something apart.

Also thanks to Oriol Jimenez for his very inspirational presentation at GDG DevFest in Barcelona and DroidconES in Murcia later this year. You can find more good advices there (if you understand Spanish).

The second life of the ExoPC slate

Almost two years ago Intel aproached developers in Barcelona with the mysterious tablet called ExoPC and very early version of MeeGo operating system. Some lucky developers walked out with the device and were able to start hacking on this touch screen enabled netbook tablet (indeed this device is powered by the Intel Atom x86 processor which used to be the heart of Netbooks). It was not very convenient to use, because MeeGo operating system never reached its maturity and was abandoned. There was no viable alternative for a long time. One could install Ubuntu or Windows 7 but those operating systems were not well prepared for operating without keyboard or mouse.

ExoPC running Windows 8

There surely was a place for Atom powered x86 tablets in the market and I never gave up on this device. Some new opportunities emerged soon. While most people are abandoning netbooks today, ExoPC still resists this trend, mainly because of two reasons: touchscreen, more than average resolution of 1366 x 768 pixels and a decent 2GB of RAM. Two new (or heavily refreshed) operating systems appeared as an alternative OS for this device: Android 4 and Windows 8.

Android, starting with Ice Cream Sandwich version (4.0) offers an interface optimised for phones and tables without additional hardware buttons (like Home, Back, Menu, Search, etc.) and was also released as a source code. This let developers build custom ROMs and some older devices with unlocked bootloaders (i.e. Samsung Galaxy S, Nokia N900) got their more or less working version of the new Google operating system. The important step in this case was the release of the Android Atom x86 optimised image by Intel, allowing better integration of Android software for developers. As a non-expert in ROM cooking I cannot really tell if this image could help the Android X86 project, but it would be quite logical to assume so.

Downloadable Android x86 Atom optimised images

Meanwhile, before anyone in the broader public got to know that Microsoft is cooking it’s own tablet, the Redmond company started commercialising the well known ExoPC as an early Windows 8 developer device. It is still a cheap and viable alternative for the Microsoft Surface. The advantage over the current version of the MS Slate is that ExoPC runs the full version of Windows 8 (Not the Windows RT), which allows you to use all the apps compatible with the previous edition of the Windows OS. The downside is that the ExoPC slate might not be fully compatible with the future Windows 8 apps.

ExoPC in the aftermarket

It supports multi-touch, but only with 2 touch points, while the new system might require as much as 5 touch points. Windows 8 also aims at devices that can normally do much more than the PC used to do. There are plenty of sensors that help Smartphones be very useful in everyday life and will be (or already are) a part of Windows-8 compatible devices.

But the best part comes here. Even if you have installed Windows 8 on the ExoPC, you can still use it as an Android device. And this is something much better than BlueStacks implementation of the Android OS, which might not always be up to date, but especially will not give you the full Android experience.

So you can install the Android 4.0 on this device, preserving the current Windows installation. This is quite simple process which you can do in a couple of steps described in this thread (in German).

If you’re not familiar with German or cannot understand what Google Translate provides you, do this:

  • Download this ISO image
  • Free some space on your disk
  • (you can do it resizing your current system partition in Control Panel > Administrative tools > Computer Management > Disk manager)

  • Make a bootable USB and boot it
  • Choose an option to install Android
  • Create a partition manually on the free space (ext3)
  • You will need to connect a keyboard to pass through this step (sic!), but it’s actually better to have it connected already at boot to avoid funny effect on the console screen.

  • Choose to install GRUB
  • When it asks if to add the Windows partition to the bootloader, select yes
  • Install the system in the R/W mode

You can restart and begin using Android (isn’t that great!?). Well, until you find some issues. There aren’t many, but depending on how you use Android, they might be a bit painful. A list of a few of them below.


Linux’s Grub will overwrite Windows Bootloader. You will still be able to start both systems, but all the functionality of the Windows 8 bootloader (changing driver signing, safe mode, etc.) will not be available. That might be a bit of a deal, but if you installed Windows 8 on top of Windows 7, then probably you will see the old text-based bootloader that was installed on the partition instead of MBR. If you restore the Windows 8 bootloader in the MBR, you will not be able to launch Android. There should be some way to do it manipulating the startup items (I recommend EasyBCD) but I had no luck in this matter.

The power/sleep button

Sometimes it’s difficult to wake up the device when it went to sleep. From my experience it starts behaving normally after prompting the “Power-off” dialog. To show it, “double-click” the power button.


The battery life is not astonishing. Because the device warms up significantly, independently of the usage, I suspect the CPU scaling is not very well supported. It doesn’t seem to take advantage of the “sleep” or “suspend” state, so it’s better to turn it off while not using. It might also happen that the system will not report the current battery state (it might stall at the initial value) so you might suddenly run out of battery (this is quite obvious though). This issue only happened two or three times for me. Restarting the device fixes it.


Not all apps will be available for this version of android, especially those which use android NDK (unlike Java, this the C++ part of code that is only suitable to the CPU architecture chosen at the compile time). The examples are many games, Skype, and whatever software that makes a high use of processing power.

To address this last issue, there is a version of the ExoPC ICS, with the built-in ARM emulator (the CPU architecture used in most Android smartphones). It is still in the experimental phase, but after a half-an-hour test seems to work good for me (download ISO here). There are still some apps that will not run (probably other requirement stated in the app manifest) but even without those few missing apps ExoPC slate is now a very versatile device that can be used as a testing device for programmers, or a “couch leisure centre”.

Choose your favorite application

I’ve been an enthusiast of alternative software solutions since the beginning of PC era, where Microsoft software, although dominating, wasn’t the only right path. Since mobile phones became smartphones, I also expected them to be modular and configurable in areas of user preference, so I welcome the possibility of exchanging the system default application by the one offered by 3rd parties. This is not common feature among all the smartphone OS-es but highly desirable where user has some non-standard requirements.

I for instance like browsing internet using Opera Mobile which gives me unified experience among many platforms, synchronizes links, saves the mobile data usage. The same situation happens with Swype keyboard, which supports my native Polish language with error correction. There are more good examples but I get puzzled with the complexity of this approach sometimes, and even as an Android developer, I cannot understand options that the system gives to me.

Case I: Web Browsing

I’ve installed Opera and Firefox browsers on my Android phone. The reason for installing the first one was explained above. The latter was convenient because of the Firefox Sync feature which lets me access my PC browser data transparently. I still might try another one as none of the browsers above allow me to preload a few pages in the background, while browsing twitter or news from my email. I often try to achieve it, but usually the system closes browser in the background and I need to load pages again, what is very frustrating if I’m in a place with low network coverage.

Back to the point. I click the link in my Slashdot newsletter and the well known pop-up appears.

Choose your favorite browser

I want to use the Android browser by default, so I mark the “Use by default” box and choose the first browser. The browser window opens and exactly the same dialog pops up for the second time. Strange right? This might look like an error to an average user but as a developer I know there are various “Intents” that open the browser (called “action” in the window above). I repeat my choice and the web page loads in the browser. The same will happen later when opening some Youtube link, Doodle, Twitter, etc. At some point it might become annoying, because if you have installed some application to handle certain content better than the browser, then why all those questions?

In the PC world some similar mechanism exists although it is more file-centered than action centered. When you are installing a new Video or Image application, you can choose during the installation process if it should be associated with the certain file types (unless it’s a bad application that forces you to use it with some files). This mechanism was field-tested over many years and proved to be very successful. Since Android OS knows what a certain application can do while installing it, maybe it would be a good idea to ask the user at this point. This would not require any changes in already published applications. It could be much better than showing dialogs which are often meaningless if the “action” context is not clear.

Said that, I’d also appreciate to be able to choose the application again in some situations (like browsing with Opera when I only have access to 2G network). This is not possible unless developers explicitly create the chooser for the action (using Intent.createChooser).

Case II: Contacts

I’ve installed some additional programs for handling my contacts data. One of them Everdroid (SyncML service, known to me previously as Mobical) for synchronising my Contacts and Calendar data (that worked great Nokia many phones for at least 8 years), and another Go Contacts replacement for my contacts book so I could merge duplicates easily. Here’s what happened when I wanted to add a new contact to my address book.

  1. System prompted me to choose a program which will manage this contact. Not sure what to do, I’ve chosen the the default app. Then the system asks me which email account do I want to add it to (3 email accounts present on my phone). I was confused, decided to go back.

    Choose your account to add a contact

  2. I’ve tried the same with Contacts Go and it shows me 3 accounts from above plus a “Phone” as a last option, just like if I was suffering from the lack of choice.

  3. I’ve chosen Everdroid now and it asks me again if I want to add it as an Everdroid contact or Google contact.

That seemed pretty complex already with the default app so I’ve decided to uninstall the additional programs to avoid confusion. Unfortunately all the contacts downloaded from SyncML server with Everdroid got deleted with it. Surprised?

There are plenty of services that maintain their own lists of contacts as Skype, Facebook. Twitter, etc… On some phones they might even be listed together with other contacts in a unified form and be deleted when you get rid of a certain account or application. But I’m more keen to believe this is fair in case of Facebook. Twitter, Skype, as they also provide some service or content, which becomes the platform for communication. If I create a contact in my phone book (or maybe better “contacts book”), I want it to persist there, unless I decide to delete it one day, not the application who created it.

As a result I stopped using additional contact management tools, and finally agreed to use my Gmail area for managing all the permanent contacts. Apart from Android, this also works flawlessly on iPhone and even on older Nokia phones (using MS Exchange server settings for Gmail).

In areas where data is sensitive, it’s sometimes better to trust the provider of your device/OS and try to dig in the possible options of default applications before switching to 3rd party solutions. Replacement applications might be very rewarding if you choose them wisely, but if you’re less lucky, you might just add another unnecessary layer of problems and complications.

The end of the Symbian era

Heavy clouds seem to have been hanging over the Symbian platform since February 11 this year, when the new CEO Stephen Elop announced that Nokia has chosen Windows Phone for its devices as the main operating system in the future. It was obvious for some that Symbian’s, as well as Qt’s end have been called. Although, Nokia still claimed that it’s formerly dominant platform will still be evolving and the Qt platform will be there.

I’ve lost my job as a Symbian developer at the beginning of the year, and I was wondering if there’s a place for a Symbian/Qt developer in the market yet. I’ve trusted Nokia’s promises. I’ve decided to continue with the Qt framework for development. I’ve been attending events that gathered people interested in that technology (starting in 2009 with the Meego long weekend Barcelona, followed by the Symbian Exchange and Exposition in 2009 and 2010, volunteered at Symbian stand at MWC in 2010, attended Nokia Dev Day at MWC 2011, Qt labs in Madrid in April this year, Intel AppUp labs for Meego in February and June), I’ve been observing trends in freelance projects ( and yet trying to search for opportunities locally. Unfortunately all of these intents (robotic laugh here) were unsuccessful. Some of the clients I’ve talked to were very interested in Qt development at the beginning (March-June) but soon they all changed their decisions to go away from native development towards HTML5 or simply drop the Symbian project as not worth the investment. By the end of August there were virtually no signs of interest in Symbian/Qt development.

In the meantime I was still working on my own projects for the Ovi Store (BiCitizen , Siberdrome, Solitarius) so I didn’t just lose my time thinking of the wasted opportunities. Although, it was obvious that at some point I will have to move elsewhere as the promises of Qt for the next billion were too vague. Having in mind previous Nokia’s promises about Qt, I guess it was not worth wasting the time to wait for another market opportunity. Now, that even Intel moved away from the Qt platform with Tizen, please raise your hands up, who are still planning the mobile Qt project soon.

I must say I’ve achieved something more than decent in the Ovi Store. “Solitarius” game has been downloaded more than 350.000 times in over 200 countries and other game, “Siberdrome” (only Symbian^3) almost 30.000 in last 3 months. But If I see similar games on the Android Market, (i.e. this Solitaire game) which achieved over 10 million downloads, it’s just hard to compare the range of success.

Nokia World event is approaching so we can expect the appearance of the Nokia Windows Phone, but is the Windows Phone the best direction for the Symbian/Qt developers?

I’ve worked with Symbian C++ since 2006. At first using the Visual Studio but then the Carbide/Eclipse environment since it was enough stable to be usable (which dates back to 2007) and finally accustomed myself to it’s flexibility and extensibility. Qt SDK came with the custom IDE that couldn’t be compared to any other IDE with which I’ve worked with so far. Although fast and well designed, it was sometimes inconvenient. Qt APIs are great on the other hand so I couldn’t complain too much about developing with the formerly-Trolltech’s SDK. It was a huge step forward from the obsolete Symbian C++ environment.

Having all this baggage I’ve brought with me from Nokia, I’ve decided to step away from it and started the Android development. This is probably obvious for those who did the same, but what a relief it was to come back to this great open-source Eclipse IDE. How nice to see many APIs and classes resemble those from Qt, and have those XML layouts which are not so far from Qt layouts and Qt-Quick. Already at the beginning I felt like I’m one leg in the Android ecosystem. Being able to quickly compile and package multi-language application with support for multiple resolutions and well-defined backwards compatibility, I was so happy I almost peed in my pants*… I wonder if heads of Nokia thought about this convenience for a while, while deciding to make a change of environment for the developers. Maybe the biggest enemy was actually a close friend here.

I’ve never taken Nokia’s decisions personally and was never angry at the changes in their plans and shifts of strategy. While living in Spain, I’ve watched how Spanish government had to make serious cuts in the public sector recently to save the country’s economy. Having seen the movement of “Indignados”, protesting against decisions of the government, sometimes in a very inappropriate way, I’ve decided it’s just a wrong to outrage. Showing that you can live well to someone who put you in a very difficult situation is much healthier response than revenge.

At the moment, that’s for sure, none of my friends wants a Symbian smartphone anymore. One of them who went to a few stores to get advices on smartphones recently, heard from sellers to get out of Symbian (not to mention allusions to the human waste). Those I know still choose other brands in spite of the reasonable effort I put to tell them something good about Nokias. My girlfriend is a great example here. She got two of her pictures into the contest for August. People are impressed with the quality of the N8’s pictures, but they get put off when they hear the “S” word.

This way I’ve joined the club of the green mushroom-like avatars, waving my hand to the new world. I don’t say goodbye to Nokia forever. Maybe we will cross our paths in the future. Maybe I will actually use one of the technologies they develop. But even now, eight months after the February 11 announcement I’m still confused which development platform they try to focus on. Is it Windows Phone? Is it Qt? Is it S40 with J2ME?

*Not for warmth