JTM JTM - 1 month ago 9
Android Question

Why does moveCamera cause an exception when called outside of the getMapAsync method?

I am working on an app that allows users to put tags on a Google Map. To do this, I need to be able to move the map's camera position to certain latitude/longitude coordinates. Here are the related methods:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_map_screen, container, false);
mMapFrag = (SupportFragmentManager) getChildFragmentManager().findFragmentById(R.id.mapFragment);
mMapFrag.getMapAsync(this);
CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(mLat, mLon));
mMap.moveCamera(center);
return view;
}

@Override
public void onResume() {
super.onResume();
mMapFrag = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapFragment);
mMapFrag.getMapAsync(this);
CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(mLat, mLon));
mMap.moveCamera(center);
}

@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}


moveCamera() causes a NullPointerException. Does anyone have an idea of why this is happening?

Answer

Callback onMapReady() gives the inflated/generated map object that you can use in your code which is a async callback. Till then the map object remains uninitialized.

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    map.moveCamera(center);
}

change onMapReady() code with above snippet.

Also, if you wish to do that on your onResume also, then you can check if the map object is null and if it is null

if(mapFrag == null){
    mapFrag = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapFragment);
    mapFrag.getMapAsync(this)
}

Use above snippet in your onResume() That should work.