13

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.

6
  • I believe you can't draw anything outside the main thread. Check this out: android-developers.blogspot.com.br/2009/05/…
    – Bilthon
    Nov 6, 2012 at 16:14
  • Yes, you are right, but I add overlays in UI thread and then call postInvalidate on mapView, there is only computations in separate thread.
    – Bracadabra
    Nov 6, 2012 at 16:19
  • you probably need a run somewhere around
    – njzk2
    Nov 6, 2012 at 16:20
  • and a final MapView as well
    – njzk2
    Nov 6, 2012 at 16:21
  • 2
    chances are that the mapView has not been attached to the window, before that the your thread is getting finished
    – nandeesh
    Nov 6, 2012 at 17:05

1 Answer 1

32

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()).

1
  • Thanks! Using post, this becomes really simple and useful. Feb 13, 2014 at 4:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.