Thursday, February 5, 2009

Careful w/ Java ME Screen Updates: Don't Trust Your Emulator

Be careful when updating a Screen (Alert, Form, List, TextBox) in Java ME (a.k.a. J2ME). I ran into a problem recently where I wanted to make a minor run-time adjustment to a Form in my app. I originally had the code update the Form while the old version of it (pre-update) was already displayed, then call setCurrent() to set the newly updated Form as the current Displayable. It worked fine in Sun's Wireless Toolkit emulator, but when I deployed to a real Sony Ericsson phone, the call to setCurrent() on the updated Form appeared to have no effect. In other words, the old, unchanged Form still showed. The problem lies with the fact that the specification does not define the behavior when a Displayable is changed while visible:

From http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/lcdui/Screen.html:

"It is recommended that applications change the contents of a Screen only while it is not visible (that is, while another Displayable is current). Changing the contents of a Screen while it is visible may result in performance problems on some devices, and it may also be confusing if the Screen's contents changes while the user is interacting with it."

First I tried a couple alternatives like setCurrent(null), which helps neither according to the spec nor based on my own testing. The best solution appears to be to create a second Screen (or Form in my case) and setCurrent() on it when it's ready. I was hoping it wouldn't come to that, but sometimes you just gotta bite the bullet and use a new object.

Happy coding.
Copyright 2011 by William Cain