IdleSun's Weblog

November 18, 2010

How to use an Java enum like an integer (for Android Message.what)

Filed under: Android,Java — idlesun @ 4:52 am

Java enum is powerful. However, it is tricky if you want to use it as integer just like in C/C++. Actually, it is not easy at all because Java enum elements are objects. So it is best to use Java enum as enum. But what about the case you need to pass it back an forth as an integer. One example is when you want to use enum for a ‘what’ of Android Message. Lets say you have defined the enum, WhatAbout, like this:

enum WhatAbout { ART, LIFE, MONEY, WORLD };

And you want to sendMessage to someHandler like this:

someHandler.sendMessage(updater.obtainMessage(WhatAbout.ART.ordinal(), 0, 0));

As you can see enum’s ordinal() method solves the issue. Now look at the receiver side. Here is the code for handleMessge() method of someHander

  public void handleMessage(Message msg) {
    if (msg.what == WhatAbout.ART.ordinal()) {
      // Do something about ART
    } else if (msg.what == WhatAbout.LIFE.ordinal()) {
      // Do something about LIFE
    } else ...

It will work, but looks ugly. Using switch must be better. However, unfortunately, the ordinal() method cannot be a case expression because it is not a constant expression. So here is my trick to get around that restriction and use switch:

  static WhatAbout[] wa = WhatAbout.values();

  public void handleMessage(Message msg) {
    try {
      switch(wa[msg.what]) {
      case ART:
        // Do something about ART
      case LIFE:
        // Do something about LIFE
    } catch (Exception x) {
      // Handle ArrayIndexOutOfBoundsException exception

The point is having an enum value array instantiated and use it in the switch expression.


November 11, 2010

Android SharedPreferences.edit().commit() lies! Not really.

Filed under: Android,Java — idlesun @ 5:37 am


This post has been moved to my new blog.


Blog at