Search code examples
androidgoogle-mapsandroid-fragmentsnullpointerexceptionsupportmapfragment

Initializing map within fragment


I am having a problem initializing my map. The map fragment is inflated into the FrameLayout of the main activity. I keep getting a null pointer exception within the setUpMapIfNeeded() method.

activity_main.xml

    <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical"> 

`         
        <include layout="@layout/toolbar"/>

        <FrameLayout
                android:id="@+id/frameLayout"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"></FrameLayout>
    </LinearLayout>



    <android.support.design.widget.NavigationView
            android:id="@+id/navigation_view"
            android:layout_height="match_parent"
            android:layout_width="wrap_content"
            android:layout_gravity="start"
            app:headerLayout="@layout/header"
            app:menu="@menu/drawer"
            />

</android.support.v4.widget.DrawerLayout>

map_fragment.xml

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">


    <fragment
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/map"
            tools:context=".MapFragment"
            android:name="com.google.android.gms.maps.SupportMapFragment"/>

</LinearLayout>

MainActivity.java

switch (menuItem.getItemId()) {
                case R.id.shop:

                    MapFragment mapFragment = new MapFragment();
                    android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                    fragmentTransaction.replace(R.id.frameLayout,mapFragment);
                    fragmentTransaction.commit();

                    break;
                case R.id.list:
                    ListFragment listFragment = new ListFragment();
                    android.support.v4.app.FragmentTransaction fragmentTransaction1 = getSupportFragmentManager().beginTransaction();
                    fragmentTransaction1.replace(R.id.frameLayout,listFragment);
                    fragmentTransaction1.commit();

                    break;
                case R.id.points:
                    Toast.makeText(getApplicationContext(),"Global card selected",Toast.LENGTH_SHORT).show();
                    break;
            }
            return true;
        }
    });

MapFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.map_fragment,container,false);

    //Check if GPS is enabled
    locationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
        Toast.makeText(getContext(),"GPS enabled",Toast.LENGTH_SHORT).show();
    }else {
        showGPSDisabledAlertToUser();
    }

    setUpMapIfNeeded();
    return view;
}

 private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the map.
    if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        //I get a null pointer exception at this point, no map it gotten
        mMap = ((SupportMapFragment)getActivity().getSupportFragmentManager().findFragmentById(R.id.map))
                .getMap();
        // Check if we were successful in obtaining the map.
        if (mMap != null) {
            setUpMap();
        }
    }
}

Solution

  • Take look at my repo for mapTab here. It shows how to initial the google map for in the fragment.

    Sample code:

    public class MapTabFragment extends Fragment {
    
        private SupportMapFragment mMapView;
    
        public static MapTabFragment newInstance(String param1, String param2) {
            MapTabFragment fragment = new MapTabFragment();
            return fragment;
        }
    
        MapView mapView;
        GoogleMap map;
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View v = inflater.inflate(R.layout.fragment_map, container, false);
            // Gets the MapView from the XML layout and creates it
    
            MapsInitializer.initialize(getActivity());
    
    
            switch (GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity())) {
                case ConnectionResult.SUCCESS:
                    Toast.makeText(getActivity(), "SUCCESS", Toast.LENGTH_SHORT).show();
                    mapView = (MapView) v.findViewById(R.id.map);
                    mapView.onCreate(savedInstanceState);
                    // Gets to GoogleMap from the MapView and does initialization stuff
                    if (mapView != null) {
                        map = mapView.getMap();
                        map.getUiSettings().setMyLocationButtonEnabled(false);
                        map.setMyLocationEnabled(true);
                        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(43.1, -87.9), 10);
                        map.animateCamera(cameraUpdate);
                    }
                    break;
                case ConnectionResult.SERVICE_MISSING:
                    Toast.makeText(getActivity(), "SERVICE MISSING", Toast.LENGTH_SHORT).show();
                    break;
                case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
                    Toast.makeText(getActivity(), "UPDATE REQUIRED", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    Toast.makeText(getActivity(), GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity()), Toast.LENGTH_SHORT).show();
            }
    
            // Updates the location and zoom of the MapView
    
            LatLng sydney = new LatLng(-33.867, 151.206);
    
            map.setMyLocationEnabled(true);
            map.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 13));
    
            map.addMarker(new MarkerOptions()
                    .title("Sydney")
                    .snippet("The most populous city in Australia.")
                    .position(sydney));
    
            return v;
        }
    
        @Override
        public void onResume() {
            mapView.onResume();
            super.onResume();
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
            mapView.onDestroy();
        }
    
        @Override
        public void onLowMemory() {
            super.onLowMemory();
            mapView.onLowMemory();
        }
    }
    

    XML for this:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">
    
        <com.google.android.gms.maps.MapView
            android:id="@+id/map"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:name="com.bojie.materialtest.fragments.UpcomingFragment"/>
    
    </RelativeLayout>