JFMG JFMG - 1 year ago 149
Android Question

Can't change container ID of fragment SupportMapFragment

I developed an app with a Google map and a navigation drawer. When I start the app the map is shown and the user can open the navigation drawer.

When the user clicks on the first item in the navigation drawer, the map should show up, in case he switched to another fragment before. However, when I call the map fragment, my app is crashing with the following error code:

java.lang.IllegalStateException: Can't change container ID of fragment SupportMapFragment{36a7826b #0 id=0x7f0e007a}: was 2131624058 now 2131624057

What I do in the navigation drawer in
to show the map is:

.add(R.id.fragment_container, supportMapFragment)

It works fine for other fragments but not for the map fragment. The map fragment is hard coded in xml to show it from the beginning and instantiated in the onCreate methods as follows:
supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

All my other fragments are instantiated by calling
new MyFragment();
and they extent

Any advices and hints on how to fix the crash and show the map are very appreciated.

Answer Source

Instead of adding and removing map, it is better to hide and show it.

Before of all it is because of performance and user interface issues: when you add map to activity - it will take some time to actually render map on screen.

You can achive this by

SupportMapFragment supportMapFragment; // field

supportMapFragment = (SupportMapFragment)getSupportFragmentManager()

// To show map fragment instead of your content fragment

// And to hide it

If you are really need to add and remove map, you should do it programmatically, instead of declaring MapFragment in xml statically.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download