Question

I have a really complicated app that has various different functions. One of these functions include a google maps tab. The app is structured in such a way that each tab is a fragment. In this particular case I am having trouble declaring my google map object to grab my current location data.

Here is the relevant code

public static class GpsClass extends Fragment{
    View rootView;
    private GoogleMap mMap;
    
    public static final String ARG_SECTION_NUMBER = "section_number";
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        if (rootView != null){
                ((ViewGroup) rootView.getParent()).removeView(rootView);
            }
            try{
                rootView = inflater.inflate(R.layout.gps, container,false);
                mMap = ((SupportMapFragment)getActivity().getSupportFragmentManager().findFragmentById(R.id.mymap)).getMap();
                mMap.setMyLocationEnabled(true);
                
            } catch(InflateException e){
             
            }
            return rootView;
        }
    }

In this codes implementation I get a Null Pointer exception when I try to declare mMap. If I remove the getAvtivity() call the eclipse tells me I can't make a static reference to a non-static method. If I remove the mMap lines my app works with a google map in one tab (the other tabs implement other things which all work).

Was it helpful?

Solution

Can you include your layout xml?

If your map fragment is SupportMapFragment (com.google.android.gms.maps.SupportMapFragment), use:

mMap = ((SupportMapFragment) getFragmentManager ().findFragmentById (R.id.map)).getMap ();

or

if your map fragment is MapFragment (com.google.android.gms.maps.MapFragment), use:

mMap = ((MapFragment) getFragmentManager ().findFragmentById (R.id.map)).getMap ();

EDIT: The actual answer to the OP's question: Make sure you're using the right class name for the Map Fragment when declaring it in your layout XML.

OTHER TIPS

Try this

GoogleMap mMap = ((SupportMapFragment) getFragmentManager()
                .findFragmentById(R.id.map)).getMap();

and in your xml

<fragment
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    class="com.google.android.gms.maps.SupportMapFragment" />
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top