Alex Rivera | Logout

SupportMapFragment - cannot cast from Fragment to MapFragment

Asked 2013-04-14T20:45:10.943
18

Trying to put together a little MapFragment in an activity I'm building, but am having some trouble getting it all to work. I know that the Maps api and Play services are both installed correctly, as I did the test tutorial and everything worked fine.

Following the documentation here, I'm running into the following problem: In my setUpMapIfNeeded method, I can either use getFragmentManager() or getSupportFragmentManager(). When I use the getFragmentManager(), Eclipse is cool with it but when I run, I get a NoSuchMethodError saying that the method is undefined. When I opt for getSupportFragmentManager(), Eclipse doesn't like it and gives me the error "Cannot cast from Fragment to MapFragment". So what's the deal? Any suggestions?

private void setUpMapIfNeeded() {
    //Do a null check to confirm that we have not already instantiated the map.
    if (mMap == null) {
        mMap = ((MapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
        if (mMap != null) {
            //do things to the map
            mMap.addMarker(new MarkerOptions().position(LOCATION).title(EXTRA_URL));
            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(LOCATION,15));
            mMap.getUiSettings().setZoomControlsEnabled(false);
        }
    }
}

Let me know if there's any other code I can provide and I'll be happy to post it quickly.

Edit
Report

1 Answer

82

I can either use getFragmentManager() or getSupportFragmentManager().

There should be no debate here. If getSupportFragmentManager() is available to you, then you are using the Android Support package's backport of fragments, and this is the method that you must use.

When I opt for getSupportFragmentManager(), Eclipse doesn't like it and gives me the error "Cannot cast from Fragment to MapFragment".

That is because you should not be using MapFragment. You are using the Android Support package's backport of fragments, and therefore you must use SupportMapFragment.

answered 2013-04-14T20:52:01.133

Your Answer