What is triggering this Exception instance: “java.lang.IllegalArgumentException: The observer is null.” and how could it be avoid?

元气小坏坏 提交于 2019-11-30 04:00:58

This problem was introduced in Android 4.0.3, and the Observable class was changed to throw an exception when an observer was released more than once. It has been reported as a bug and can be read here: http://code.google.com/p/android/issues/detail?id=22946.

The easiest way to work around this problem is to wrap the underlying adapter and avoid multiple releases.

@Override
public void unregisterDataSetObserver(DataSetObserver observer) {
  if (observer != null) {
    super.unregisterDataSetObserver(observer);
  }
} 

But that will not work in all cases, e.g. ExpandableListView has an internal adapter that cannot be accessed. An alternative solution here is to wrap the ExpandableListView and catch the exception. This solution worked for me, and I have yet not found any side effects.

public class PatchedExpandableListView extends ExpandableListView {

  public PatchedExpandableListView(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  @Override
  protected void onDetachedFromWindow() {
    try {
      super.onDetachedFromWindow();
    } catch(IllegalArgumentException iae) {
      // Workaround for http://code.google.com/p/android/issues/detail?id=22751
    }
  }
}

I made the silly mistake of thinking that none of my classes were mentioned in the trace, but LoadingDataView is one of them. It doesn't show in the original trace but another that was related.

Inside that class there is an anonymous ArrayAdapter that was where the incident is happening so I added this as a work around:

@Override
public void unregisterDataSetObserver(DataSetObserver observer) {
    if (observer != null) {
        super.unregisterDataSetObserver(observer);
    }
}

And it seems to work now although I'm still not sure why this method was called twice.

Although, for now on I'm going to use Fragments as much as I can ;)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!