JFMG JFMG - 26 days ago 9
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
onItemClick
to show the map is:

getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, supportMapFragment)
.addToBackStack(null)
.commit();


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
Fragment
.

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

Answer

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()
   .findFragmentById(R.id.map);

// To show map fragment instead of your content fragment
getSupportFragmentManager().beginTransaction()
   .show(supportMapFragment)
   .remove(yourContentFragment)
   .commit();

// And to hide it
getSupportFragmentManager().beginTransaction()
   .hide(supportMapFragment)
   .add(yourContentFragment)
   .commit();

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