Create a gist now

Instantly share code, notes, and snippets.

Sample android-support-v4-googlemaps MapFragment setup
public class MainActivity extends {
// Only one MapView instance is allowed per MapActivity,
// so we inflate it in the MainActivity and tie its
// lifetime here to the MainActivity. Package scope
// so we can grab them from different instances of map
// fragments.
// The other option was to make them static, but that causes
// memory leaks on screen rotation.
View mMapViewContainer;
MapView mMapView;
protected void onCreate(Bundle savedInstanceState) {
// only init fragment the first time onCreate() is called. Even if the Activity is
// killed / recreated, FragmentManager will add the Fragment once the Activity is back.
if( null == savedInstanceState ) {
// do not add to backstack, or user will be able to press back and
// view MainActivity's blank layout with nothing in it.
// In this case, we want the back button to exit the app.
.add(, MyMapFragment.newInstance() )
.setTransition( FragmentTransaction.TRANSIT_FRAGMENT_FADE )
mMapViewContainer = LayoutInflater.from( this ).inflate( R.layout.mapview, null );
mMapView = (MapView)mMapViewContainer.findViewById( );
public class MyMapFragment extends Fragment {
private View mMapViewContainer;
private MapView mMapView;
public static MyMapFragment newInstance() {
MyMapFragment fragment = new MyMapFragment();
Bundle args = new Bundle();
// add any necessary args here
fragment.setArguments( args );
return fragment;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView( inflater, container, savedInstanceState );
// We can't grab the MapView onCreate() since Fragment#onCreate() is
// called before Activity#onCreate() (where the MapView is created).
// We also can't do it in Fragment#onActivityCreated() since its called
// after Fragment#onCreateView(). So, we grab it every time here.
// Yes, its ugly that this fragment has to know that it lives inside
// a MainActivity.
MainActivity mainActivity = (MainActivity) getActivity();
mMapViewContainer = mainActivity.mMapViewContainer;
mMapView = mainActivity.mMapView;
// your other fragment code

Can you post your entire code? I mean the whole project

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment