Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Context problem in Android example "Google Map View"

I've tried to implement the Google Map View tutorial on the Android developer site, but I keep running into a problem when trying to display an AlertDialog when I click on the overlay image. The problem is that mContext is null when calling

AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);

in HelloItemizedOverlay's onTap method because the constructor

public HelloItemizedOverlay(Drawable defaultMarker, Context context) {
    super(boundCenterBottom(defaultMarker));
    mContext = context;
}

is never called (that I can tell) which initializes mContext. When I replace

HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable);

with

HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable, 
                this.getApplicationContext());

in HelloGoogleMaps's onCreate method in order to initialize the context, I get an exception

android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

when I try to display the AlertDialog like so:

dialog.show();

I assume this tutorial has been successfully implemented by thousands of people, so I'm at a loss why no one else has run into this problem... have I missed an important step from the tutorial?

like image 787
tronman Avatar asked Dec 17 '22 03:12

tronman


1 Answers

I think you need to pass mapView's context to the HelloItemizedOverlay constructor like so:

HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable, mapView.getContext());

There is clearly an error in the tutorial's code sample. Small errors and omissions like this are not uncommon within reference documentation, especially for a large project like Android.

like image 152
Jeff Gilfelt Avatar answered Dec 28 '22 08:12

Jeff Gilfelt