Ibrahim Yilmaz

Nov 21, 2019

2 min read

LiveData and IllegalStateException: FragmentManager is already executing transaction

Photo by Sarah Kilian on Unsplash

Hello Android Fellas,

Recently I have faced with this crash :

It seemed to be strange because all of unit tests in the pipeline passes successfully and testers run smoke tests in Test and Production environments and no crash.

It is good or bad practice it is another topic the crash happened where we want to show Dialog by using DialogFragment.

If I summary flow between entities:

Source code more or less something like that and the main problem is that it does not crash everytime:

In order to reproduce the crash, I tried to use showNow()

Still same crash happens sometimes but more than the previous one.

Problem is still not visible. But now we have more IllegalStatementException. The solution was to revert code back to previous one and have that crash less than latest version or try to dig it more.

When we check the crash log. It seems that this crash happens right after the fragment is created. It seems that it is impossible to have that because showError happens after some long running task and this should not happen. Because when Fragment is created, the value of LiveData<Boolean> is null and it should not fire any event.

It seems that something magical happens in the life cycle and resource management.

I just set the initial data for LiveData in ViewModel.

And hurra! I start to reproduce the crash!

Reason: It seems that Android somehow kills and creates the caller Fragment. But we have ViewModel and LiveData. Observer directly called right after Fragment called. While its transaction is ongoing, it tries to execute new transaction in order to show DialogFragment.

Solution: Instead of using fragmentManager(because it is activity’s supportFragmentManager), we should use childFragmentManager. In that way Android can manage to handle Fragment Transactions. The crash doesn’t happen again.

I hope this could help you.

Have fun.