ViewFlipper "Receiver not registered" Error

There is this error that plagued me for a few months. If you use a ViewFlipper, this error will pop up on Android 2.1 devices every once in a while:

java.lang.IllegalArgumentException: Receiver not registered: android.widget.ViewFlipper$1@44b6ab90

It does not affect any devices before 2.1, and so what was troubling at first was that the 2.1 source code wasn't yet released so I could't diagnose the issue. Everyone knew it had to do with orientation changes on an Activity with a ViewFlipper, but why exactly it happens isn't clear (I took my own stab at it, but was incorrect about the exact cause; it just seems to happen randomly).

Thankfully, the source has been available now for a while. Obviously, the problem is that onDetachedFromWindow() is somehow being called before onAttachedToWindow(); but how do we come up with a workaround until it is fixed at Google?

One simple solution is to override onDetachedFromWindow() and catch the error from super:

@Override
protected void onDetachedFromWindow() {
    try {
        super.onDetachedFromWindow();
    }
    catch (IllegalArgumentException e) {

    }
}

The only problem with this is that the error is thrown before calling updateRunning(). A simple workaround for this is to call stopFlipping(), as that will kick off updateRunning() without any negative side effects:

@Override
protected void onDetachedFromWindow() {
    try {
        super.onDetachedFromWindow();
    }
    catch (IllegalArgumentException e) {
        stopFlipping();
    }
}

You should only use this version of the class on Android 2.1 phones, as they are the only ones requiring the fix.

EDIT May 25, 2010: ViewFlipper bug still occurs in Android 2.2. I sure hope you didn't filter based on apiLevel == 7; better to use apiLevel >= 7.