Since you have specified the map fragment in the layout file, you can safely find it using findFragmentById
in onCreate
like so:
MapFragment mMapFragment; // this is neither GoogleMap or MapView!
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMapFragment = (MapFragment)getFragmentManager().findFragmentById(R.id.map);
initializeMap();
}
@Override
public void onResume() {
super.onResume();
// map init was already done in onCreate, will not do it twice
}
Then when you need the GoogleMap
object you ask for it and have it delivered via a callback. When the callback executes, the map is guaranteed to be not null. This will work since Google Play services library v6.5.
private void initializeMap() {
mMapFragment.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap googleMap) {
// googleMap will never be null here
// do not store it in a variable, always make a getMapAsync call
// do your map setup here
}
}
}
This is as quick as it gets so you shouldn't experience any flickering.
Note: In the original post you mentioned you had different layouts for portrait and landscape. If you really do, make sure both contain corresponding fragment IDs, otherwise you're bound to get exceptions. You also mentioned the layout was main.xml
not activity_main.xml
so make sure you use the layout you intended.