Why getHandler() returns null?

时间秒杀一切 提交于 2019-12-23 07:36:41

问题


I have got following problem. I'm drawning route on mapview in separate thread like this:

 public void drawRoute(final MapView mapView) { 
          new Thread(new Runnable() {
          public void run() {
          try {
           //Do something useful
          } catch (SomeException se) {
           Handler handler = mapView.getHandler();
           handler.post(/*show error in UI thread*/)
          }}
        }).start();
      }

But when I get handler it returns null, although in debug mode handler returned and error message is displayed. What can the problem be?

PS May be it's incorrect way to get Handler, but I couldn't find information about it.


回答1:


The getHandler method returns null because the view is not attached:

public Handler getHandler() {
    if (mAttachInfo != null) {
        return mAttachInfo.mHandler;
    }
    return null;
}

mAttachInfo is set in dispatchAttachedToWindow and nulled in dispatchDetachedFromWindow.

Instead of mapView.getHandler().post() you can use directly mapView.post() (which seems to use getHandler().post() or ViewRootImpl.getRunQueue().post()).



来源:https://stackoverflow.com/questions/13254819/why-gethandler-returns-null

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