Category Archives: Software Development

Posts about software development. Generally I use Java, PHP, and Python for development but occasionally I delve into other things as well.

Object Persistence in Codename One

One very useful feature of Codename One is its Storage class, which provides a cross-platform key-value store that can be used to store simple data (e.g. Strings, Integers, Doubles), large binary data (e.g. byte arrays of encoded movies or images), and custom data types (i.e. your own objects). Storage is not shared between applications so it is like your own persistent Hashtable that allows you to store anything you might need for your application.

The API is simple. It provides methods to read objects, write objects, delete objects, check for object existence, and listing objects that are currently stored in storage. All lookups are based on key-value lookups.

A simple example:

Storage s = Storage.getInstance();

// Save the "Hello World" string to storage
s.writeObject("mystring", "Hello World");

// Read my "Hello World" string back from storage
String hello = (String)s.readObject("mystring");

// Delete my string from storage

Just as we stored a String, we could have stored a Vector of Strings, or a Hashtable of key-value pairs, or a tree of Vectors and nested Hashtables. The only caveat is that the Vectors and Hashtables can only contain objects that can be externalized.

What Can Be Externalized?

I don’t have a definitive list of what can be externalized in Codename One, but in general, you can externalize:

  • Primitive types (e.g. int, float, long, double, byte, etc..)
  • Arrays of primitive types (e.g. int[], float[], long[], double[], etc..)
  • Strings
  • Vectors
  • Hashtables
  • Objects implementing the Externalizable interface.

Hence, if you want to save your own custom objects in Storage, you need to implement the Externalizable interface. It is worth noting that you can’t simply implement the Serializable interface as you do in regular java. You need to implement Codename One’s externlizable interface that explicitly defines how to read and write the objects to/from a DataOutputStream/DataInputStream. This is due to the fact that Codename One doesn’t support reflection. In addition to implementing the Externalizable interface, you also need to register your class with CodenameOne (via the Util.register() method) so that it knows which class to use when deserializing your objects.

Saving Custom Types to Storage

As mentioned above, any object that you want to persist to Storage must implement the Externalizable interface. If you try to save objects that don’t implement this interface it will raise an exception. If you, subsequently try to read an object that hasn’t been registered with Codename One via the Util.register() method, then Storage.readObject() will simply fail silently and return null. This will occur, if any object in the graph that you are trying to read is not registered.

The Externalizable interface requires 4 methods:

  1. getVersion() – This should return the version of your object. This will be used to record the version of the object when it is written to storage. This value will be passed to your internalize() method when you read the object so that you can handle old serialization structures properly when you modify your class.
  2. getObjectId() – This should return a unique String ID for the class (not the object as the method name seems to indicate). This should match the id that is registered with Util.register() so that it knows which class to instantiate when loading objects from a DataInputStream. But you could use anything here, as long as you use the same ID in the Util.register() method.
  3. externalize() – This method should write your object to a DataOutputStream.
  4. internalize() – This method should read your object from a DataInputStream.

Your class should also include a public constructor that takes no arguments.

Example Class:

Let’s look at a simple example class for a user profile.

class Profile {
    public String firstName, lastName;
    public int age;
    public List<String> emails = new Vector<String>();

Note that I’m making all of the members public for simplicity and to reduce code in this example. Normally you would probably make the members private and implement setter/getter methods to access them.

Now, let’s implement the Externalizable interface on this class:

class Profile implements Externalizable {
    public String firstName, lastName;
    public int age;
    public List<String> emails = new Vector<String>();
    public int getVersion() {
        return 1;

    public void externalize(DataOutputStream out) throws IOException {
        Util.writeUTF(firstName, out);
        Util.writeUTF(lastName, out);
        Util.writeObject(emails, out);

    public void internalize(int version, DataInputStream in) throws IOException {
        firstName = Util.readUTF(in);
        lastName = Util.readUTF(in);
        age = in.readInt();
        emails = (List<String>)Util.readObject(in);

    public String getObjectId() {
        return "Profile";


I want to comment on a few things here that are important:

  1. The order in which we read members from the DataInputStream in the internalize() method must be exactly the same as the order in which we write them in the externalize() method.
  2. We use Util.writeUTF() to write Strings instead of the DataOutputStream’s writeUTF() method, because it handles null values. I.e. if you try to pass a null string to the DataOutputStream’s writeUTF() method, it will throw a NullPointerException.
  3. We use Util.readObject() Util.writeObject() for writing objects (like the Vector containing email addresses). DataInputStream/DataOutputStream don’t provide equivalents.

Reading and Writing Profiles

Now let’s test out our class:

Profile steve = new Profile();
steve.firstName = "Steve";
steve.lastName = "Hannah"

Storage s = Storage.getInstance();
s.writeObject("steve", steve);

Profile newSteve = (Profile)s.readObject("steve");

System.out.println("Profile first name : "+newSteve.firstName);

If you try to run this example you’ll get a NullPointerException when you try to access the firstName property of newSteve. If you retrace your steps, you’ll find that the object was written OK (you can use the Storage.listEntries() method to see what keys are stored in storage). It’s just that the line:

Profile newSteve = (Profile)s.readObject("steve");

returns null. This is because we forgot to register our Profile class with Util, so it didn’t know which class to use for deserialization. If we add the line:

Util.register("Profile", Profile.class);

at any point before we try to read the object from storage, then it will work as expected. This is a big gotcha.

Tip: If you are getting null values out of storage, you should make sure that you have registered classes for ALL objects that are being read, including nested objects.

Where to Place Registration Code?

I’m still sorting out where the best place is to store the code that registers a class with Util. Here are a few options:

  1. Explicitly register all classes that you are using inside your application’s controller (e.g. in the start() method). If your application is self contained, this may be the simplest way. However, if your app may be using classes from external libraries, you may find it difficult to identify all of the possible classes that you may need to retrieve from storage.
  2. Inside a static block for the class that implements the Externalizable interface. e.g.

    public class Profile implements Externalizable {
        static {
            Util.register("Profile", Profile.class);

    This will work, if you have referenced the class from somewhere inside your code before you unserialize the object. However, if your object is nested and its class is not referenced directly from code, then this static block may not be run before the object is deserialized (which will result in readObject() returning null).

    For example, we might load a Vector of Profiles like this:

    Vector v = Storage.getInstance().readObject("profiles");

    If we don’t explicitly reference Profile in our code, here, then this will fail (silently) because the Profile class will not be registered yet. However, if we first reference the Profile class, it will work. E.g.

    Profile p = new Profile();
    Vector v = Storage.getInstance().readObject("profiles");

  3. Other ideas? You can place the registration code anywhere you like. You just have to be aware of when/if your registration will be run vs when your objects are likely to be read from Storage.

Trouble Shooting

During my experiments with Storage, I ran across a few "gotchas" that you should watch out for:

  1. Object keys cannot be "paths". I.e., don’t include the "/" character in the key for write/readObject or you may get some unexpected results. E.g.
    Don’t do:

    byte[] b = new byte[]{'a','b','c'};
    Storage.getInstance().writeObject("bytes/foobar", b);

    Or you will get an error like: /Users/shannah/.cn1/bytes/foobar (Not a directory)

    I’m not sure if this is a bug, but it’s something to watch out for. You can use any other character you want. Just don’t use a slash!

  2. Make sure ALL objects in your hierarchy that you are saving implement the Externalizable interface (or are supported natively by CN1 eg. Vector, Hashtable, etc..)
  3. Make sure you have run Util.register() for ALL classes that will be read from storage before trying to read them from storage. If you do not do this, Storage.readObject() will fail silently, returning null.
  4. Use Util.writeUTF()/Util.readUTF() when writing/reading Strings in your externalize() method. Don’t use out.writeUTF() because this will throw a NullPointerException for null strings.
  5. Use Util.writeObject()/Util.readObject() for writing/reading objects inside your externalize()/internalize() methods. There is no equivalent in DataOutputStream/DataInputStream.

Two Months with the Nexus 7

I have now had the Nexus 7 for a little under two months so I thought I’d post a mini-review of the product.

I purchased the Nexus 7 because I needed a newer Android test device for my development and I had heard good things about it.

The Good

It is very light. Compared to my first generation iPad, it is a joy to hold while I read the web in bed.

Easy and intuitive setup. The interface of Android 4.2 seems to be much improved over my previous android device (2.2). Installing apps and switching between apps is fast and efficient.

Development is easy. Compared to my iPhone where I had to jump through an endless series of hoops, just to get my own apps running on my device, the Nexus 7 was as simple as plug it in and go.

The price. At $199 you can’t complain.

The Bad

Battery life. My first generation iPad can sit on the table unused for weeks, and still have a full battery charge. With the Nexus 7, I can put it in my bag with a full charge, and it will be empty the next time I want to use it 3 days later.

Scrolling. Compared to my first gen iPad (which is 3-year-old technology), the scrolling is jerky and sluggish in most apps. It seems that Android is still playing catch-up on the usability scale.

Soft keyboard. Once again, comparing to my iPhone and 1st gen iPad, the keyboard is more difficult to use on the Nexus 7. The autocorrect is frequently wrong, and it doesn’t seem to get as good at guessing which key I intended to type.

The Case For Light-Weight UI Toolkits

This post is motivated by a recent Reddit thread where someone posted an announcement about the 1.0 release of Codename One, a toolkit for building cross-platform mobile applications. I was quite surprised by the stream of negativity in the responses from developers who had never tried the framework, but who mistakenly assumed that they knew everything about it because they have tried other cross-platform toolkits in the past.

Before I discuss the thread itself, I just want to take a minute to talk about light-weight UIs and why they are important.

Light-Weight UI vs Heavy-Weight UI

When people refer to a light-weight user interface toolkit, they are generally referring to a toolkit where all of the widgets and components are drawn using graphics primitives using the toolkit itself. A heavy-weight user interface, on the other hand, is one where the components from the underlying platform are just placed in the user interface, and aren’t drawn manually. Swing, JavaFX, HTML5, QT, and Codename One are examples of light-weight UI toolkits. AWT, SWT, and Appcelerator Titanium are examples of heavy-weight UI toolkits.

Why Are Light-Weight UI Toolkits Important for Cross-Platform Development?

When you are developing for multiple platforms, then a heavy-weight UI will be one that addresses the lowest common denominator. If every platform has a “Text box” widget, then you can safely add a text box to your UI, and the correct widget will be shown on the current platform. But if one of the platforms doesn’t have a text box widget, you need to either say that “text boxes aren’t supported on platform X”, or you have to come up with an alternative for that platform.

With a light-weight UI, every platform can have a text box because you don’t depend on the underlying platform for the actual widget. This opens quite a bit of flexibility.

It is kind of like the difference between creating art work with stickers vs painting the art directly onto canvas. Imagine you are teaching an art class via a webcast and you have 5 different art students each with their own toolkit. These toolkits consist of a set of stickers and stamps that they have brought from their own collection, and a paint set. For the “heavy-weight” portion of the class, you would be instructing the students to place stickers onto the canvas. E.g. You might say “Now place a sticker of a dog in the top right corner”. But what if some of the students don’t have a sticker of a dog? Then you might say, “If you don’t have a dog, just use a cat. And if you don’t have a cat, then just leave the space blank”.

At the end of the lesson, the art work produced by each student would be radically different. The stickers would be different, might be different sizes, and some canvases might be completely blank if the student didn’t have the appropriate sticker.

The alternative “light-weight” lesson would just involve some paint brushes and paints. Imagine that students were able to replicate your painting perfectly. So if you paint a dog in the top corner, they will be able to paint an identical dog in the top corner of their canvas.

At the end of the lesson, then, every canvas will look more-or-less identical. At some point, you might actually tell the students to draw something different in a section that reflects their local culture. This would be fine also, and the variation would be reflected in the finished product.

This is basically the difference between a heavy-weight and a light-weight UI toolkit.

The mobile development space is getting very fragmented and form factors vary greatly. If any space needs a good platform for lightweight UI development, it is the mobile space.

Back to the Reddit Post

Responses were full of hate for Java, light-weight user interfaces, and the concept of cross-platform toolkits in general. One pervasive, yet misinformed, line of reasoning the came through in some of the frequent posters’ comments was as follows:

  1. Cross platform toolkits result in “lowest common denominator” applications that don’t take advantage of the features of any particular platform.

  2. Lightweight UIs won’t look or behave like a native on any platform so it is much better to use a heavyweight UI (i.e. wrap native components) so that the app at least looks and behaves natively.

  3. Lightweight UIs are slow! There are a million HTML5 solutions out there, but they are all laggy. It is better to just use a heavyweight UI.

  4. Cross-platform toolkits sound good at the start, but, inevitably you will hit a road block that will prevent you from achieving your goal, and have to resort to building native applications for each target platform, wasting, perhaps, a year or more of the time that you spent trying to use the cross-platform framework.

This line of reasoning appears to make sense if you don’t dig into some of the embedded assumptions. For example, #1 and #4 only hold true for heavy-weight toolkits, and #2 and #3 simply aren’t true. Let me address all of these points individually.

Do Cross-Platform Toolkits Result in a Lowest Common Denominator App?

If you develop a lightweight UI, then there is no reason why the resulting application should be the lowest common denominator of all platforms. This is because, in a lightweight UI, you are not dependent on the native widgets. You can embed native components in cases where it makes sense, but you are not limited by this. Any component in a lightweight UI can be used across all platforms, and configured to behave differently on each platform if it makes sense. Components can be created on top of a lightweight UI that don’t even exist in any of the underlying platforms. This adds a tremendous amount of flexibility and offers enormous potential.

Take, for example, the JFXtras project, which is built upon JavaFX, a light-weight UI framework for the desktop. It is a collection of components and widgets that are all light-weight (so they are truly cross platform) and they look and feel fantastic. If you wanted to develop this set of widgets using a heavyweight toolkit it would be 5 times the work, and would be impossible to maintain.

Are lightweight UIs doomed to look “un-native”?

While lightweight UIs give you the flexibility to create an app that doesn’t look native, you can come very close to a native look, if that is what you are trying to achieve. Light-weight UIs that are well designed enable you to develop themes that look and behave just like the native platform. The Swing has been doing this for years on the desktop and, while you may think that you can spot a Swing application a mile away, I am willing to bet that you have probably used many Swing applications without knowing it. Of course you can spot the ones that don’t look native – where the author didn’t place a priority on following native UI guidelines. But if you ran across one that did follow the guidelines, you would be none the wiser.

In my opinion, the Codename One folks have done a fantastic job of developing native looking themes for all of the main mobile platforms. I showed an app with the iOS theme to quite a number of savvy users and none of them could tell, at all, that it wasn’t actually using native widgets. All of the buttons look the same, and it behaved the same. This is a testament to the design acumen of their team.

And if you don’t like the look and feel, that is no problem. It is light-weight. You can override the look and behaviour of any component to conform to your preferences, if you like. Apply these changes across all platforms or only specific ones.

So, lightweight UIs certainly are not doomed to look un-native.

Are Lightweight UIs Slow?

Well, they can be, but so can heavyweight UIs. Performance depends on many factors, and if you have tried any of the HTML5 toolkits out there for building mobile apps you have probably noticed that these apps are indeed sluggish. So you might be tempted to apply the logic that since HTML5 apps are slow, and HTML5 is a lightweight UI toolkit, that all lightweight UI toolkits are slow. This is certainly incorrect. HTML5 requires very complex layout rules, and it relies on Javascript as its language that is quite a bit slower than a native executable would be. This is very hard for low-powered mobile devices to handle in a performant way. Ultimately as device performance improves (maybe in a couple years), the HTML5 performance problems will dissipate.

Codename One uses a different strategy that is much more similar to Swing than to HTML. It uses 2D drawing technology of the host platform to build its components (OpenGL on iOS, etc..) which is very fast and flexible. This allows for the creation of complex user interfaces without barely any performance hit.

So, no, lightweight UIs don’t have to be slow, and in Codename One’s case, it is not slow.

Are You Destined to Hit a Wall If You Use a Cross-Platform Framework?

I have been burned. You have probably been burned. I think everyone has been burned once or twice when they start a project with a toolkit, then sometime later, they hit a wall and the toolkit just can’t be used to take the next step. Is this inevitable with a Cross-Platform framework?

The answer is, maybe. But if you choose your framework carefully, they you shouldn’t have a problem. Some key items to look for would include:

  1. Is it open source? If it isn’t open source, then the chances are you will get stuck at some point and have to abandon it.

  2. Can you access native APIs if necessary? If you can’t access native APIs, then you will likely have to abandon it at some point.

  3. Is it built on a strong, robust, and fast foundation? If it isn’t, then you’ll likely have to abandon it at some point.

If the framework hits all three of these points, then you should be OK. If you need to access a new API on a particular platform, you can just write a native plugin for that. If you run into a bug or a limitation, you can fix it yourself, as long as it is open source. And as long as the core of the framework is strong and fast, you can build your own component libraries as time goes on to extend the platform, without worrying about breaking the platform.

Most HTML5/Javascript frameworks will fail on #3. HTML5 and Javascript just aren’t robust. There are many commercial cross-platform frameworks out there also. I would be careful with those.

In the few months that I have been working with Codename One, I have found the platform to be open and robust. If I find something that it doesn’t do, it is usually quite easy for me to add it myself. The fact that they allow you to write native plugins, wrap native components when necessary (to add to the UI), and develop my own libraries and components that run on top of it, give me confidence that there is no “wall” that I could hit in the future that would be a show-stopper.

4 Ways to Consume JSON Web Services in Codename One

I just released a Javascript bridge for Codename One that allows you to communicate easily back and forth between Java and Javascript. This library may be absorbed by the Codename One core at some point in the future, but for now it is very easy to include it with your own projects.

There are countless ways that this Javascript bridge can be used to add value to Codename One applications. In this post, I will show how it can be used as an alternate way to consume JSON web services.

Codename One already includes a JSONParser class that allows you to, quite easily, consume a web service and parse its output into a tree of Hashtables and Vectors (I will demonstrate this method below). So why use the Javascript bridge to solve an already-solved problem? The answer is: Just to prove that it can be done.

Method 1: Load data using ConnectionRequest, and parse data into Hashtables and Vectors using the JSONParser class

E.g. Loading JSON feed from Youtube for Most Popular Videos

The benefit of this method is that it is a 100% Java solution that should work the same across all platforms. It should also be very fast and efficient.

Note: Codename One offers a Result class that makes it much easier to query the result of the JSON parser. Read more about it in Eric Coolman’s blog post.

The amount of code required to consume and parse the request is not really relevant because it can all be wrapped in a single method with a callback for the result.

Method 2: Load data using WebBrowser and use Javascript’s JSON.parse() function to produce a JSObject

E.g. Loading JSON feed from Youtube for Most Popular Videos

The benefit of this method is that it is easier to obtain nested content stored in a JSObject than in a tree of Hashtables and Vectors. E.g. The same example as above (to obtain the make of a car in the result set) could be carried out on 2 lines:

JSObject response = (JSObject)context.get("JSON.parse(document.body.textContent)");
String make = response.getString("people[0]");

Method 3: Pass a JSON String into JavascriptContext.get() to obtain a JSObject

E.g. Loading JSON feed from Youtube for Most Popular Videos

This is really just a hybrid of the two approaches, and it is useful if we’ve already loaded the JSON data and have it in a String. E.g. perhaps we used ConnectionRequest to load data from a Web Service, and some of the Data is JSON and some of it is another format. In any case, this method assumes that we have a String of JSON data and we want to turn it into a JSON object so that we can work with it.

Then we can pass the string directly to JavascriptContext.get(), and the WebBrowser component will handle all of the parsing.

JSObject response = (JSObject)context.get(jsonString);
String make = response.getString("people[0]");

Method 4: Load data with the WebBrowser and parse it using JSONParser

E.g. Loading JSON feed from Youtube for Most Popular Videos

This is really the inverse approach of method 3 above. In this case we load JSON data in the WebBrowser, retrieve it as a string using JavascriptContext.get(), and then parse it using the JSONParser class.

Develop for Mobile or Die!

If you develop software that is designed to be used by Humans, then you are now required to develop mobile-friendly user interfaces.

In 2011, a mobile user interface was a luxury. In 2012, it was a nice add-on. In 2013, it is a requirement, or your software will be headed for the junk bin. Smart phones are now ubiquitous, and tablets are taking the place of the laptop in many contexts. People are becoming savvy to what can be accomplished with a tablet, and their expectations have been significantly raised for all software that they use.

Of course, the desktop (i.e. computers with mouse or trackpad and keyboard) is not going anywhere. It is just being reserved for those heavy-duty tasks that cannot be performed with a touch device like (and this list is shrinking every year) video editing, software development, and word processing. One class of application this can now be handled wholly via a mobile interface is the CRUD application. And if it can be created for mobile, it should be created for mobile – or your users will complain (either silently by seeking out other solutions, or loudly in email).

One trend that I noticed in 2012, was a shift of user gripes originating from users using IE to users on mobile devices. At first, my canned response was: “please use a computer, not your iPad, for using this database”. Of course, the software worked on iPad, but it wasn’t optimized for the platform so it was a little painful to use. And even under the best of conditions, users will find a way to break a UI. At first, there were some valid reasons why the app had to be used on a computer. But at this point, there are no longer any technical barriers in the way of providing a mobile interface to a (mostly) CRUD application.

Transitioning CRUD Applications to Mobile

The easiest way to transition a CRUD application to mobile, is to use an HTML library like jQuery mobile. It provides a slick UI that is very similar to native. The simple act of adding a UI in jQuery mobile that is tailored specifically for mobile users will eliminate most gripes. The larger buttons and fields, combined with a more familiar mobile workflow will make your users much more at home inside your application.

Unfortunately, the similarity to native applications will invariably lead your users to start requesting features that they have seen in other native applications. E.g.:

  • We want to be able to take videos with our phone and upload them into the database. Can we do that?
  • We want to be able to use the database without being online. Can we do that?
  • We want the database to be able to track our movement and velocity and store this in the database. Can we do that?
  • The application is kind of sluggish when loading pages and scrolling, etc…. Can you improve it?

The list of feature requests is not even limited to things people have seen before … the possibilities are endless.

While HTML5 is improving all the time, and it does technically support offline apps, and limited video access, it is still very flaky, and does not approach a native experience yet. Ultimately, when your users start asking for native-like features, you need to start looking for a way to build an application that is treated as a first-class citizen on the mobile platform of choice.

Mobile Platform of Choice??? Do I really need to Choose?

The next step after outgrowing your HTML5 mobile interface (with jQuery Mobile), is to look at your options for developing a native application. I’m using “native” in a very loose sense here. Really what I mean is an application that is installed on a mobile device in the same way as the platform’s native applications. This could be an application that is written directly using the platform’s SDK or using some other toolkit that ultimately builds an application that can be installed on the device.

If you are developing a CRUD application for an organization (like I usually am), you may or may not be able to dictate that your users use a specific device. In my case, I usually can’t… or if I try it is a world of pain dealing with people that use “the other” platform. Therefore, developing separate applications for each platform is not really an option (or good use of resources). I’m still choked at having to venture outside the web-box, much less create multiple versions of the same app.
At the minimum you’ll need to develop versions for Android and iOS (but BB and WinPhone users might get on the gripe-wagon, so watch out!!).

Phone Gap

As a web developer, naturally, the first thing I looked at was Phone Gap. It allows you to develop your application using the same web tools (HTML/Javascript/CSS) and deploy it as a “native” application. The native application is essentially just a thin wrapper around a web view component. It provides some additional libraries for working with the device’s hardware like accelerometer, GPS, video camera, etc.. Because it is just a web view wrapped in an app, you can use all of the same libraries (e.g. jQuery Mobile if you like) for developing the app. If you’re lucky you won’t have to modify the existing web app at all.

Building the applications for Phone Gap can be a little more involved, as different platforms need to be set up differently, and some even differences in the application code to make it work. However, the PhoneGap build service is available to provide building in the cloud for multiple different devices. This should ease the “pain” substantially.

Phone Gap will probably give you enough flexibility to add most features you need in a CRUD application. However, you may run into issues with performance. Javascript/HTML runs much more slowly (and noticeably so on low-powered mobile devices) than native code. Facebook’s shift away from HTML5 apps to native apps last year is a key indicator that, for mobile at least, HTML5’s time has not yet come. This performance will be most noticeable when performing scrolling operations and in some transitions, but it can rear its head anywhere.

To make matters worse, on iOS, the UIWebView component doesn’t use the same Javascript engine that is used in the Safari web browser. It is substantially slower. So, by moving your application from the Web into a PhoneGap app, you will be facing a performance penalty directly from Apple.

If you are running into performance problems, or you require native features that just aren’t offered in Phone Gap, you may need to graduate to the next level: Real Native Apps

“Real” Native Apps

First, let me define what I mean when I say “Real” native apps. I mean applications that are compiled down to native executables on the supported platform. I disqualify Phone Gap from this category (and the many other HTML5 in WebView solutions) because the actual code is running inside a web sandbox.

If you have reached this level, you should at least take the various platforms’ native toolkits for a spin so that you understand how they work. Each platform offers its own unique vision for their mobile worlds. And some concepts don’t transfer easily from one platform to another. Developing for iOS is very similar to developing for Mac OS X. You use Xcode and Interface builder to develop your application logic and user interface. Generally the entire user interface is contained inside a single Nib file, and you can use the many UIController classes to control the user interface. iOS includes many useful frameworks such as CoreData which makes it easier for you to develop CRUD apps on iOS.

Android, on the other hand, is an XML jungle. The UI is defined in XML files, and so is the application configuration. It is a much more open environment than iOS, in that it is set up to encourage applications to share its components with other applications on the system.

Blackberry and Windows Phone provide their own models, but I’m not familiar with either of these platforms.

In the course of auditing the respective SDKs you’re bound to observe the elephant in the room: All of these SDKs use different programming languages. iOS uses Objective-C, Android uses Java, Windows Phone uses C# (or C++ depending on version), and Blackberry uses C++ (at least for BB10… older versions use Java).

This makes it very difficult to share code across multiple platforms. Since I don’t have the resources to maintain separate code bases for each platform, I need to either pick a single platform and run with it, or look for a solution that will allow me to develop for all of the platforms with a single code base (remember I have disqualified Phone Gap and its HTML5 ilk already if I have reached this point).

Luckily there are options:

  1. MonoTouch provides C# bindings for pretty much the entire Cocoa Touch API (iOS). It also provides bindings for Android.

  2. J2ObjC is a tool developed by google to convert Java code to Objective-C so that it can be reused for iPhone development.

  3. Oracle ADF provides a full development toolkit that allows you to build for most mobile platforms. It uses an embedded JVM for business logic, and Phone Gap for the UI…(should we disqualify this out the gate because of Phone Gap?)

  4. Appcelerator Titanium provides a cross-platform solution that provides Javascript wrappers around native components. It is different than Phone Gap in that it doesn’t run inside a web view, it merely uses the native platform’s built-in Javascript interpreter and bindings to access native components.

5. XMLVM is a low level converter that allows you to convert code between many different languages. It provides compatibility libraries for working with Android and iOS. In my opinion, this is the most ingenious software development of the past 10 years.

  1. Codename One. Codename One allows you to write mobile applications in Java and compile them into native executables for most major platforms. It uses XMLVM under the hood for its iOS port. This is, by far, the best option right now for cross-platform native mobile development, and I’ll explain why in the following section.

If you know of other options, please let me know.

These solutions can be grouped into 3 categories:

  1. Tools that assist in porting from one platform to another, but don’t provide a full development solution. These include J2ObjC and XMLVM. While these are very interesting projects, it our aim is to be able to build a cross-platform web app, then these projects won’t get us there directly. If you are developing a tool or SDK that is designed to help you and others build cross-platform apps, then these projects may be of great interest to you.

  2. Tools that allow you to share your business logic between platforms, but ultimately require a rewrite of the user interface for each platform. MonoTouch falls into this category. Really MonoTouch is a solution for C# developers who want to develop for iOS and would prefer to use C# instead of Objective-C. It isn’t really a solution for building cross-platform mobile applications.

  3. Tools that provide a full solution for developing cross-platform mobile applications. Codename One, Oracle ADF, and Appcelerator Titanium fall into this category.

Oracle ADF

I have watched videos and read documentation for Oracle ADF, but have never actually tried to build an application with it. There are a couple of show-stoppers for me on this platform:

  1. It is commercial. I wasn’t clear on the license costs, but it makes it sound like they are hoping to make large license fees off of large enterprises.

  2. They use Phone Gap for the UI. If I’m at this point (looking for a native solution and Phone Gap won’t cut it), then, ADF doesn’t meet the requirements.

Appcelerator Titanium

Appcelerator Titanium is a clever project. I spent some time last year using the desktop version to develop some desktop applications using Javascript and CSS (the desktop version actually works more like Phone Gap than their mobile version does… it embeds a web view in a native window). Ultimately I abandoned all of my desktop Titanium projects as it was apparent that the Appcelerator people were putting all of their development resources into their mobile edition and letting the desktop version languish.

The mobile edition has some promise and apparently it has their full weight behind it. The concept of using Javascript bindings for native components is interesting, although it leaves open some of the same performance problems that plague PhoneGap. From what I have read in various forums and blogs, Appcelerator mobile apps do run into performance and memory problems if they are not developed carefully. Although they seem to be getting better with each release.

Appcelerator provides an API that generalizes commonalities between different platforms, but it enables you to write plugins that are platform specific if you need to use features of a platform that aren’t available in the API. This blog (presumably by someone who knows titanium – “titaniumninja”), argues that Appcelerator isn’t really a “Write Once Run Anywhere” tool:

Titanium isn’t a write-once-run-everywhere platform. As Appcelerator’s guys use to say, its aim is to be a write-once-adapt-everywhere tool, since, while using a common high level language and API, it enables the exploitment of platform specific features when needed. This philosophy is clearly visible in the API, as we have entire sub-namespaces dedicated to either iOS, or Android. This allows adapting our mobile applications to the platforms where they’re executed, thus avoiding a write once, suck everywhere effect. Moreover, the possibility to develop custom native extensions to the framework opens up a wide range of development scenarios, ideally allowing us to create user experiences that are practically undistinguishable from those of applications developed with native SDKs.

This description/warning seems realistic and makes me optimistic about the platform. If you are a Javascript/CSS ninja, then Appcelerator will probably provide an accelerated path to a mobile application, while not inhibiting you with a glass ceiling. I really like to be able to build native plugins for high-level frameworks. Otherwise I feel like I’m one feature request away from having to abandon the platform.

Without having dug too deeply into Appcelerator’s API, there are a couple of negatives (when compared with Codename One or native app development) that appear right off the bat:

  1. Javascript is a bitch to debug compared with managed languages like Java and C#.
  2. Memory management and performance are likely issues, and you may need to dig into the “native plugins” crutch sooner than later to resolve such issues.

If Appcelerator was the only cross-platform solution on the market, you can bet I’d be using it.

But Codename One exists…

Codename One

I have been developing with Codename One for a couple of months now. Based on that, you would probably guess that it was my choice for developing native mobile apps. You would be correct. When you line up all of the other options for development (native SDKs, Appcelerator, ADF, etc..), Codename One wins on almost every front.

What do I like about Codename One?

Codename One is the only true write-once-run anywhere solution out there (for native apps). It uses OpenGL (I believe on all platforms, but any graphics toolkit could be used if something better came along) as the foundation upon which its rich set of components are built. This makes it much easier to port to different platforms than, say Appcelerator, because all of the widgets are light weight (Similar to Swing in the Java Desktop world). The user interface can be styled using themes to look exactly like the native platform, and they provide native themes for all platforms for which they produce apps.

Applications are written in Java and they are compiled into native binaries (on iOS they use XMLVM to produce native C code that is compiled into an ARM binary using LLVM). They provide plugins for Netbeans and Eclipse, as well as a simulator to be able to run and preview your apps right in the IDE. The resource editor application also provides rich GUI development tools for forms and themes.

Basically, they have provided for the entire development cycle. They don’t leave you hanging. They even provide a cloud build server for you to build your applications without having to install the native SDKs. This allows Windows users to build iOS apps, and Mac users to build Windows Phone apps. (Initially I was concerned that I wouldn’t be able to do my own builds offline, but this was unfounded, as I was able to, without too much difficulty, set up my own build environments for iOS and Android… and I have no reason to believe it will be any more difficult for Blackberry).

The performance of CodenameOne apps is near native, and may even be faster than native apps in some case (e.g. Java method calls are 3 to 4 times faster than Objective-C message calls).

All of these features (the GUI builder, simulator, build server, Netbeans plugins, etc..) was enough to make me try it. But I stayed for the API. CodenameOne’s API is a joy to use. Their founders have a real knack for building clean UIs that are easy for developers to figure out. It appears to be heavily influenced by Swing, but with all of its demons exorcised. As an experiment I set out to write an application using the Android SDK, the iOS native SDK, and Codename One separately to get a feel for the differences in the API. By far, the Codename One API provided the most fluent experience.

In places where the API doesn’t support something, Codename One provides native interfaces that allow you to develop your own native libraries that interoperate with Codename One. This means there is no glass ceiling. Anything you can do on a native platform, you can do on Codename One.

If you are a Java developer, you really should be using Codename One to develop your mobile apps. Otherwise you are wasting precious resources and excluding potential users and platforms from enjoying your application.

If you are not a Java developer, and you want to develop mobile apps, I still think that you would be better off learning Java and jumping on the Codename One wagon than spend your time developing for another platform.

Codename One iOS Offline Build Project

To build upon my last post, I have encapsulated the steps to build an iOS application offline (i.e. without having to send to the CodenameOne build server) into a single ANT script that can easily be installed on your local system, and imported into the build.xml file of your CodenameOne application.

The CodenameOne folks have provided me with space in the CodnameOne incubator subversion repository to host this project so it will be available to everyone.


The Offline Build Tools project includes some scripts to perform the building of CodenameOne applications on any computer running Mac OS X 10.7 and Xcode 4+. The applications it produces should be equivalent to those apps produced by the build server in every way (including Native Interface support). Please let me know if you run into any cases that the build tools do not support).


Before you can use the offline build tools in your Netbeans project, you need to install the build tools project. You only need to do this once. Installation involves only two steps:

  1. Check out the offline-build-tools project from the SVN repository:
svn checkout codenameone-build-tools
  1. Run the ant install script:
$ cd codenameone-build-tools
$ ant install

This will check out the entire CodenameOne SVN repository into the “tools” subdirectory so that it can be used for building your projects. It may take some time to complete as the SVN repository is quite large.

When the installation is complete, you should notice that it created a file named “build-ios.xml” inside the codenameone-build-tools/dist directory. This contains a ready-to-use ANT target that can be imported into the build.xml files of your CodenameOne applications.

Adding the “build-for-ios-device-locally” Target to Your Netbeans Project

Now that the Offline Build Tools have been installed, you can freely add the resulting ANT target to your CodenameOne application. If you haven’t already done so, you’ll need to create a CodenameOne project in Netbeans (e.g. File > New Project, and select “Codename One” as the project type).

Under the “Files” tab in Netbeans, you should be able to see and open the “build.xml” file for your project. Just add the following <import> statement anywhere inside the <project> tags of the build.xml file:

<import file="/path/to/codenameone-build-tools/dist/build-ios.xml"/>

Now, if you right click on the build.xml file, and select “Run Target” > “Other Targets”, you will see a target named “build-for-ios-device-locally”. Select this target to build your project.

Alternatively, you can build from the command line using:

ant build-for-ios-locally

Note: If building from the command line, you may need to set your JAVA_HOME environment variable to point to your JDK’s Home directory. e.g.

export JAVA_HOME=/Library/Java/JavaVirtualMachines/1.7.0u10.jdk/Contents/Home

If you’re not using CodenameOne yet, for building mobile apps, you really need to start. It is the only solution that currently allows you to write apps for all major platforms in a performant way.


This project is meant for development purposes. I created it to allow me to be able to test and develop patches for CodenameOne without having to submit them to the CodenameOne people to be applied to the server. The current settings work directly off of the CodenameOne trunk, which is probably not ideal for production apps … it is bleeding edge.

I recommend using the CodenameOne build server for all production builds as it has been refined with (probably) some optimizations, and it makes it much easier to build on many different platforms with great ease.

Building CodenameOne iOS Apps Locally

Note: This post discusses the mechanics around building CodenameOne iOS projects locally. See my subsequent post for information about a project that automates this entire process.

I’ve been playing around with Codename One quite a bit recently, as it appears to offer enormous potential in the field of mobile development. One initial stumbling block that I had with CodenameOne was that you needed to use their build server to actually build your application. Since the code is open source, it is actually possible to build it yourself, but there were no build scripts available to automate this task, and the only instructions on how to do still required a fair bit of tinkering to get it to work.

Last month, as an exercise, I created an iOS port for CodenameOne that runs on Avian (a light-weight AOT compiler for Java), just to see if it was possible. It was indeed possible, and I was able to successfully get applications built with CodenameOne up and running using Avian on my iPhone. After some benchmarking, I found that there wasn’t a compelling performance difference between my Avian port and the XMLVM port that they are currently using on the build server. Therefore, rather than sink a lot of time into a competing port, it would be better to start working with the “official” XMLVM port for my development.

Today, as another exercise, I built an ANT target that would automate the building of a CodenameOne application for iOS on my local machine. To use it, you simply copy and paste the target into your Netbeans CodenameOne project’s build.xml, and modify some of the properties to point to the proper locations in my environment. Most of the logic is based on the build instructions that had previously posted in the CodenameOne forum.

Installation Prerequisites

You will need the following components to be in place on your system before you can use the ANT target:

After these are installed, the ANT target should work for any application you try to build.

Step 1: Checking out the CodenameOne repository

You simply need to open Terminal and check out the codename one repository. The following example creates a directory called “src” inside your home directory, and checks out codenameone in a directory named codenameone-read-only inside this src directory.

$ cd ~
$ mkdir src
$ cd src
$ svn checkout codenameone-read-only

At this point, the CodenameOne repository trunk will be located at ~/src/codenameone-read-only.

Step 2: Install XMLVM

The iOS Port project of the CodenameOne repository includes a copy of XMLVM that you can install if you don’t have it installed yet. It is located at:


You can find installation instructions for XMLVM at

Update Dec. 14/2012: Currently you need to use the xmlvm distribution that is included inside the iOSPort directory. Installation instructions are still the same:
$ cd /path/to/codenameone-read-only/Ports/iOSPort/xmlvm
$ sudo ant
$ sudo ant install

The above instructions would install xmlvm at /usr/local/bin/xmlvm

Once you have XMLVM installed, you should be able to use the ANT target in your own projects.

Step 3: Add Build Scripts to iOSPort

The ANT target depends on a Python script to be able to add files to Xcode projects from the command line. You will need to download this buildscripts directory, and copy it into the codenameone-read-only/Ports/iOSPort directory (i.e. the final location would be


You can download these build scripts here

You also need to add a template for the Main application entry point into the iOSPort directory. Create a file at codenameone-read-only/Ports/iOSPort/ with the following contents:

Adding the Ant Target to Your Project

  1. Create a CodenameOne application project in NetBeans (if you haven’t already).
  2. Open the build.xml file for your project. (e.g. you can click on the “Files” tab, then expand the tree node for your project, and double click the “build.xml” file.
  3. Paste the following snippet into the build.xml file. It can appear anywhere inside the <project>…</project> tags.
  4. Modify the codename1.repo.path property to point to the codenameone-read-only directory (i.e. where you checked out the CodenameOne repository to).
  5. Modify the xmlvm.path property to point to the XMLVM binary on your system.
  6. Modify the ant.path property to point to the ANT binary on your system.
  7. Modify the python.path property to point to the python binary on your system.

Building your Project in NetBeans

Once you have successfully added the the ANT target to your build.xml file, you should be able to build the project.

  1. Click on the “Files” tab.
  2. Right click on the “build.xml” file in your project, and select “Run Target” > “Other Targets” > “build-for-ios-device-locally”
  3. Wait. It should open Xcode with your project when it is finished building.
  4. You should be able to just run or build your project in Xcode like it is a normal iOS project. It will take some time (usually about 5 minutes per build), because XMLVM produces a couple thousand Objective-C files and includes them in the Xcode project. (Don’t worry, LLVM will strip out all unused code so that the resulting binary isn’t too big).

*Note: It doesn’t seem to like building for the simulator. You can only build for an iOS device currently. I believe this is because it includes a library, zbar, that is only compiled for arm devices (not the i386 emulator).

iOS Signing Identity & Provisioning Profile

It is worth noting that you will need to set up Xcode to use your iPhone Developer identity, or it will stop you in your tracks. You will also have to set up a provisioning profile if you are doing development builds. This was a real pain in the ** to get right (in fact it was probably harder than writing the ANT script), but there is lots of documentation on this on both the CodenameOne site and the Apple site (and all around Google too).

You’ll need to make sure that your App ID (set in Project Properties in NetBeans) will need to begin with your the unique code that your provisioning profile is set up with.

Current Limitations : Native Interfaces

This build script doesn’t currently build native interfaces that you may have developed as part of your application. Native Interfaces need to have some special glue generated at build time for them to work, and the code and specs for this glue have not been released. If you are using native interfaces, you’ll need to use the CodenameOne build server in order to access them.

I am working on replicating that glue so that Native interfaces will work in local builds, and will post it when complete. An inability to develop native interfaces locally is a major impediment to being able to contribute to the CodenameOne project. It is critical that *all* build functions can be performed locally or I fear that it will be difficult for a community to form around this wonderful project.

More Thoughts on Avian vs XMLVM for iOS

I’ve only been using CodenameOne for a couple of weeks now, and I’ve been experimenting with both Avian and XMLVM on iOS. As I mentioned above, the fact that XMLVM actually outperforms Avian on many benchmarks means that I may not pursue the Avian port much further. However there are a few aspects of using Avian that have come to my attention in the short time that I’ve been playing with CodenameOne:

  1. Debugging and Stack Traces are better on Avian. XMLVM currently isn’t a whole lot of help if you run across an exception. It states that stack traces are currently unavailable and simply prints the error message. Avian, on the other hand, will give you a full stack trace, which makes it easy to debug problems.
  2. A full Java runtime environment. In XMLVM there are a few things that don’t work the way you expect if you’re used to the Java runtime environment. E.g. I was trying to print debugging information to the console using the familiar System.out.println() only to find out that this doesn’t seem to output anything in XMLVM. (Not sure if there’s anything special I need to do to get this working). Also, things like loading resources from Jar files using Class.getResource() and Class.getResourceAsStream() don’t work on XMLVM. You need to use equivalents from the CodenameOne API which are thin wrappers over native methods that do the same thing.
  3. Well that’s all I have come up with so far..

Building Locally vs Sending to the CodenameOne build server

It is important for me to be able to build my CodenameOne projects locally because I want to start contributing to the project and I need to be able to test my changes to the CodenameOne core without sending them into Shai to add to the build server. However, for production releases, I still recommend using the build server. They have taken the time to sort of all of the kinks and add many optimizations that I just don’t have time to work out. Their build server is also a bit faster than building locally.

Avian vs XMLVM: AOT Java on iPhone Benchmarks

In my last post, I discussed the results of a benchmark comparison between XVMLVM and Avian both solving the Towers of Hanoi problem on an iPhone 4s. Originally it looked like XMLVM ran slightly faster, solving the problem in 35 seconds (vs 42 seconds for the Avian version).

The code that I used for the benchmark are as follows:

Codename One controller contains the actual benchmark timing code:

However, today I decided to try writing the same code directly in C using CodenameOne’s native interfaces. This way I would have a baseline with which to compare the performance – so that we know just how much performance we are giving up by using Java instead of C to write an iPhone App.

The native code for this benchmark is as follows:

And it was used in a CodenameOne controller to actually perform the benchmark timing as follows:

I was initially frustrated to find that the C version of my benchmark ran in 0 milliseconds (compared to about 35,000 ms for my Java version compiled with XMLVM/GCC and 42,000ms for my Java version compiled with Avian). Something had to be wrong. I checked to make sure that it was actually calling my function. It was indeed running the function. I tried increasing n to ridiculously large values (3000000), but it still ran in 0ms.

As it turns out the GCC/LLVM compiler was outsmarting my benchmark. Because the benchmark function didn’t return any values to to the caller, and didn’t affect any state outside of its local variables, it decided that the entire function could be replaced with No Op. This is sort of like a compiler’s version of “if a tree falls in the woods and nobody sees it…”. As far as GCC is concerned, the tree didn’t fall.

To solve this problem, I added a static variable that is incremented each time the function is called. This way the compiler wouldn’t be able to eliminate the code as dead. The revised C code looks like:

After modifying the benchmark to update a static variable (so that the compiler could no longer cheat), I was able to finally get a benchmark result. However, this discovery cast a shadow over my previous benchmark results, so I decided to modify the Java version to update a static variable (so that no cheating could take place).

The modified Java version looks like:

This time around, I found that Avian was marginally faster than XMLVM (about 15% faster).

The results of the revised benchmark are as follows:

Hand-coded C version (GCC/LLVM) 31.7 seconds
XMLVM version 65.8 seconds
Avian version 57.1 seconds

Changing to Use Object Methods Instead of Static Method Calls

After posting the above results in the XMLVM forum, Arno (the creator of XMLVM) suggested I try changing the TowerOfHanoi.move() method to not be static. I made the change as follows:

And the the actual benchmark timing code changed to:

Clearly, Arno had some insider knowledge about how the method dispatching works because this produced wildly different results for both XMLVM and Avian:

XMLVM version 40.2 seconds
Avian version 77.4 seconds

So XMLVM, in this test, narrows the gap between native C function calls, and its own method dispatching performance. (Less than 33% difference, which is negligible in the scheme of things). Avian clearly doesn’t handle object methods as quickly as it does static methods, and this really brings to a forefront Joel Dice’s comment that little benchmarks like this don’t really mean much. Applications do much more than perform recursive functions with simple integer arithmetic. The true performance of an application comes down to many factors including graphics, networking, memory allocation, floating point calculations, etc…

These experiments, for me, at least reaffirm that Java is a viable platform for developing for mobile. It should *not* suffer from the same performance problems that current HTML5 solutions do.

A Victory Lap for Java

The benchmarks above make it look like Java is at a disadvantage when compared to purely native apps written in Objective-C (even if in some tests XMLVM appears to have almost caught up). But these benchmarks are comparing to C function calls, which are very fast. What if we change the benchmark to use Objective-C messages. This, is not really fair, since it is well-known that Objective-C message passing is much slower than typical function and method dispatching. Nonetheless, let’s make try, if for no other reason than to know just *how* slow it is.

I changed the Native code as follows, so that it is using message calls for all recursive calls.

Not surprisingly, this benchmark ran much more slowly than the previous version:

Objective-C Message Calls 154.5 seconds

Thoughts in Summary

AOT-compiled Java (either by Avian or via XMLVM) produces performance that is comparable to native C code. It may actually perform better, but these benchmarks are very narrow in scope. The relative performance of XMLVM and Avian seem to vary widely depending on which operations are being performed. XMLVM seems to handle object methods very well, whereas Avian seemed to have slightly quicker dispatching of static methods.

In any case, I don’t have any reservations about the performance of CodenameOne in relation to native apps. Whether it uses XMLVM, Avian, or some other solution for deploying Java to iOS, it should be able to provide sufficient performance for any sort of application.

See Also

  1. CodenameOne + Avian = Java on iOS – My blog post discussing my experiment to create an Avian port for CodenameOne to run on iOS
  2. XMLVM is Actually Pretty Fast – My blog post discussing my initial benchmark results comparing Avian to XMLVM
  3. Codename One Avian Project on Github

XMLVM is Actually Pretty Fast

DISCLAIMER: The Benchmark results in this post turned out to be flawed due to GCC/LLVM optimizations unduly favouring XMLVM. Please see the next post where I discuss the corrected benchmark and associated results.

In a previous post, I described some of my experiments in creating an Avian port for CodeNameOne. As mentioned in the post, one of my motivations was to see if I could improve on the performance of the current default iOS port which uses XMLVM to convert the Java code into C code (and ultimately compiled with Xcode). I had a hunch that binaries produced via the XMLVM translation would be slower than an AOT compiled Java implementation because of the way it works (It converts VM byte code operations into C stack operations in the C language – which would presumably produce much less succinct code).

After some tedious conversion of XMLVM runtime library calls to JNI calls, I was able to successfully build my Avian iOS port for CodeNameOne. Next I created a simple application (based on the CodenameOne Tabbed Application template) that runs the Towers of Hanoi problem, and built two versions of the app:

  • One using the CodenameOne build server (which uses XMLVM in its build process)
  • – Another one using my Avian, Proguard, and Xcode.

The Benchmark Results

The results were surprising.

I ran both apps on my iPhone 4s which is on iOS 5. The app is set to solve the tower of Hanoi problem for n=30 moving from pole 1 to pole 3. The time required to complete the problem was pretty consistent. On average, the XMLVM app would complete the problem in 35 seconds, and the Avian app would complete it in 42 seconds.

NOTE: After fixing the benchmarks so that GCC/LLVM *had* to run all of the code, it turned out that Avian was actually a bit faster.

This is quite the *opposite* of what I expected. While I’m a little disappointed in the results, I am also encouraged. This means that the performance of apps developed in CodeNameOne for iOS (using their build server) is actually quite good. I can be confident that I am building on a solid foundation.

I posted these results on both the CodenameOne forum and the Avian forum and a few explanations for the outcome were proposed. One explanation, that makes sense is that the XMLVM build benefits from optimizations of GCC and LLVM such as method inlining, loop unrolling, autovectorization, code motion, and intelligent register allocation. Avian’s AOT compiler, being simpler, and far less mature doesn’t implement any of these optimizations so the resulting binary is actually working at a slight disadvantage.

Joel Dice (creator of Avian) did note that a simple benchmark like Towers of Hanoi is not really helpful for determining real-world performance. A full comparison on real-world tasks would be more informative.

UPDATE: The Benchmark results in this post turned out to be flawed due to GCC/LLVM optimizations unduly favouring XMLVM. Please see the next post where I discuss the corrected benchmark and associated results.

The Executable Size

Another important factor when producing a mobile app, is the actual executable size. Why install a 100MB application when you can get the same app in under a meg. I used Proguard on the Avian build to trim down the code size (so we don’t need to include the entire JRE. XMLVM, also uses a number of optimizations to ensure that dead code isn’t included in the final executable.

My test app came out at 3.5MB for the XMLVM build, and 6.0MB for the Avian build. So XMLVM seems to have won here again.

What Now For the Avian Port

Now that I have established that the current XMLVM implementation of the iOS port is quite fast indeed, there is little need to continue to develop an Avian port. This exercise was academic in nature, and I’m satisfied that I have achieved my goals, which were:

  1. Can it be done? (i.e. Create an Avian port for CodenameOne). The answer was YES!
  2. To learn about the CodenameOne architecture. I learned a lot.
  3. To learn about the Avian architecture. I learned a lot here too.
  4. Find out whether the performance would be dramatically improved by using an AOT java compiler instead of XMLVM -> C -> Xcode. The answer, for now, was NO. XMLVM is pretty fast as it is.

Despite that fact that my experiment didn’t yield any performance improvements, there still might be some advantages to developing apps on the Avian stack. Off the top of my head, these include:

  1. A more familiar Java environment. JNI instead of XMLVM’s runtime when interacting with the native environment.
  2. JDK7 support. I’m not actually sure what version of Java I could use with CodenameOne’s XMLVM implementation. It is at least Java 5, but I don’t think it is at Java 7. I notice that they use Apache Harmony for the iOS port.
  3. Perhaps better debugging and exception handling. Shai Almog noted that XMLVM doesn’t support ClassCastException and doesn’t check cast validity. Its stack traces are also a bit cryptic when you get an exception.

Up Next For Avian/iOS

I am keen to try my next experiment with Avian and iOS: Combining my Java-Objective-C bridge with Avian to produce a Java solution that is similar to MonoTouch. I.e. Where you write the code in Java but still use the Apple development tools for the UI. This wouldn’t be a cross-platform solution like CodenameOne produces, but it would be useful, I think.

Up Next for CodenameOne

Time to develop some real-world apps!


Apple’s Walled Prison

I endure it because they make great software. I endure it because I have become dependent on their ecosystem. I endure it because there’s money in developing software for their platform.

But I am ever so close to just saying “Forget it” and moving on.

Apple’s simplistic DRM solutions for iPhone reduce the utility of the device by about 90%. They don’t even seem to consider what happens when you have 2 or 3 people in a family, all with separate iPhones all synced to the same computer. They don’t seem to care about people who have a desktop and a laptop computer and need to be able to copy files and apps to their phone from either of these devices.

Just a glimpse of my life with Apple’s walled prison last night. I was developing some sample Apps using CodeNameOne, NetBeans and Xcode. I have the full dev environment on my laptop, but my iPhone happens to be paired with my Desktop. When it comes time to “test” out my app on MY phone, I need to first register my phone with Apple as a development device, then set up and install a provisioning profile onto the phone. This part was about an hour of mucking around that I would like to have back.

Then it comes to copying my test app to my phone. Of course, I can’t do that from my laptop. I need to kick my wife off the desktop computer so that I can first copy the app to the desktop computer. From there I should be able to copy the app to my phone with no problems, right? Well not so fast. Apple is a firm believer in Murphy’s law, and a simple “copy” just wouldn’t cut it.

First attempt it tells me that my phone is not authorized for the apps on this computer, so i would need to erase my entire phone to continue. I discovered that iTunes was signed into the iTunes store under my wife’s account – which was the source of the problem.

After logging out of the iTunes store and logging back in with my account, I make another attempt. At this point it stopped pushing me to erase my entire phone, but it seemed to be complaining that several apps were not authorized for this computer. E.g. My Gmail app and my Netflix app. I guess I installed them straight from the App store. It prompted me to authorize them, at which point I entered my iTunes username and password. It took the password and then informed me that the apps still weren’t authorized. 4 or 5 times around this circle, I finally decided to just go with the “Don’t Authorize” button. After all, my goal here is to simply copy ONE test app that I had written onto my iPhone.

After opting to “not authorize” my apps I was informed that I would be required to delete the apps. At this point I just wanted to proceed so I said “fine, delete them!”.

After that I was able to copy my test app onto the phone and it ran quite nicely.

So at the end of the day, my test app written with CodenameOne runs great, and the number of installed apps on my phone has been reduced by 25%. No gmail, No netflix…. I guess I’ll just have to install them again and go through this dance once more.

This is not an isolated incident. Just the most recent in my lifetime of troubled interaction with my iDevices. In the past I have given up on such difficult tasks as
1. Copying a video from my computer to my iPad.
2. Copying a song from my computer to my iPhone
3. Copying a PDF from my computer to my iPad.

Up until now, I had solved the problem by just reducing the number of things that I do with these devices. I was down to just checking email. But since the Apple gods have deemed my unauthorized to use my Gmail app, I guess I won’t be doing that either.