Android Maps V2 MapView inside custom fragment (NPE)

android, google-maps, maps

Solution

I succeeded in including a MapView (v2) in a custom Fragment itself embedded in a ViewPager. In my case, the MapView is included in the Fragment layout file. I have had to call lifecycle methods on MapView (`onCreate()` called `onCreateView()` from the Fragment), and to call manually `MapsInitializer.initialize(context)` to avoid a `NullPointerException` from class BitmapDescriptorFactory (to get the bitmap for markers). This last trick is strange, and I don't know why the Map system isn't properly initialized itself without this call, maybe it's just a bug in the current version ...

In my case I haven't had any `NullPointerException` in `onResume()` or `onDestroy()`.

Problem

I do not want to use or extend `SupportMapFragment` or `MapFragment`. I have my own base class with a bunch of code in it. The documentation clearly states that when someone uses `MapView` by itself, all corresponding lifecycle methods (`onCreate()` `onResume()` etc.) should be called. Most of the lifecycle methods in a `Fragment` are similar to an `Activity` but when I switch back and forth between my `Fragment` I eventually get an obfuscated NPE in `onDestroy()` or in `onResume()` methods. All the samples provided use an `Activity` with a `MapView` but not a custom `Fragment`. Has someone done that already? Can you provide sample code of a `MapView` in your own `Fragment`class?

Original source

Related problems