Reputation: 2537
I am getting a non-fatal exception on firebase Crashlytics:
Non-fatal Exception: java.lang.IllegalStateException
Fragment already added
Here is my related code:
var isFragmentAdded = false
for (supportFragment in supportFragmentManager.fragments) {
if (supportFragment::class == fragment::class) isFragmentAdded = true
}
if (isFragmentAdded || fragment.isAdded) {
transaction.show(fragment)
} else {
transaction.add(R.id.contentFragment, fragment)
}
transaction.commitAllowingStateLoss()
As you can see, I check if the fragment was added in two ways before add the fragment. Why does this issue appear? (I was not be able to reproduce it on my devices or emulators)
Upvotes: 2
Views: 417
Reputation: 5788
Right, we had the same exception in our crashlytics logs as well. There are few possible ways to resolve it.
1.
So in most cases it's because commitAllowingStateLoss()
. And it's not only because "saved state" during your transaction as documentation says. It will use previous state to recreate Fragment
and from our experience it's directly related to the flow or Fragment
transaction.
So first of all. Remove it's usage, and fix your transaction state setting. You don't want to use commitAllowingStateLoss()
in place where your fragment could be in stack and you want to reuse it. (Like in your snippet above).
2.
I'm pretty sure your issue is because of point 1 above. However there is another reason, which already mentioned in the comments. FragmentTransactions
are committed asynchronously. Therefore, you need to call executePendingTransactions()
For more information refer here.
Upvotes: 2