简体   繁体   中英

IllegalStateException Fragment already added

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)

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM