Log

One of the problems of developing for mobile phones is that functionalities that work in the emulators don’t work in the real devices. Some devices manufacturers offer on device debug functionality for their SDKs but the majority don’t.

On regular Java development programmers normally use the “System.out.println” to print variables, state information or even exceptions. The problem with this approach is that it doesn’t help on the actual devices because there isn’t any console to print on.

After trying different methods on several projects I finally ended up creating a small static class called Log. This simple class as one main method:

  public static void log(String text) {
    if (logText == null) {
      logText = new String();
    }
    Date date = new Date();
    logText = date.toString() + ":" + text + "\n" + logText;
    // also print to console in simulators
    System.out.println(text);
  }

So now in my projects instead of using the “System.out.println” i always use the Log.log method.
But now you ask how can i see this information in the device? for that i added a new method that creates a form and shows it on the screen.

public static Displayable showConsole(){
    if (formLogConsole == null) {
      formLogConsole = new Form("Log");
      itemLog = new StringItem("Log:", "");
      formLogConsole.append(itemLog);
      formLogConsole.addCommand(new Command("Back", Command.BACK, 1));
      formLogConsole.addCommand(new Command("Clear", Command.ITEM, 1));
      formLogConsole.setCommandListener(instance());
    }
    current = Display.getDisplay(midlet).getCurrent();
    itemLog.setText(Log.logText);
    return formLogConsole;
  }

So whenever i need to check the console i just call the method Log.showConsole() and there it’s a form with all my logging info. I normally associate this action to a key event.
After you check the log you just press back option and return to your previous “Displayable”.

In order to use this functionality you just need to set the midlet variable of the log once in your project. I normally do this in the constructor of the project Midlet.

I also created some helper methods for handling logging of exceptions, you can check them out in the full code.

Happy logging and see you soon.

Downloads:

0 Responses to “Log”


  1. No Comments

Leave a Reply