So I have an empty fragment that contains a map fragment. Whenever I try to activate the fragment containing the map, my app crashes and returns a null pointer error on this
I searched for a lot of threads on this as I was having the same issue with older google play services. As Victor said that your class extends from fragment and it has to use another fragment defined in the layout, So best approach will be to use getChildFragmentManager()
instead of getSupportFragmentManager()
.
Also getMap() method is deprecated
now as mentioned in google docs. Please refer this for more:-
https://developers.google.com/android/reference/com/google/android/gms/maps/MapFragment.html#getMap()
Below is the working code I have tested on various devices of older play services. This will generate the default message in case of device having older google play services and in case object of GoogleMap
returns null:
class MyFragment extends Fragment
{
SupportMapFragment myMapFragment;
GoogleMap myMap;
View convertView;
FragmentManager fm;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
convertView=inflater.inflate(R.layout.mymap,null);
fm=getChildFragmentManager();
myMapFragment=(SupportMapFragment) fm.findFragmentById(R.id.myMapId);
// here instead of using getMap(), we are using getMapAsync() which returns a callback and shows map only when it gets ready.
//it automatically checks for null pointer or older play services version, getMap() is deprecated as mentioned in google docs.
myMapFragment.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap googlemap) {
// TODO Auto-generated method stub
myMap=googlemap;
startMap();
}
});
return convertView;
}
}
See this thread for more info.