Why does getHandler () return null?

I have the following problem. I draw a route on a map in a separate stream as follows:

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 the handler, it returns null, although in debug mode the handler returns and an error message appears. What is the problem?

PS Maybe this is the wrong way to get a handler, but I could not find information about this.

+7
source share
1 answer

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

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

mAttachInfo set to dispatchAttachedToWindow and numbered to dispatchDetachedFromWindow .

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

+22
source

All Articles