Few issues cause more frustration in Android development than IllegalStateException: Can not perform this action after onSaveInstanceState or null view references inside Fragments. Understanding how FragmentManager state transitions interact with Activity lifecycles is essential for crash-free UI architectures.
Enforcing FragmentStrictMode Policy (AndroidX)
Enable FragmentStrictMode in your Application or Activity class to catch illegal Fragment operations (such as target fragment violations or retain instance usages) during development:
import android.app.Application
import androidx.fragment.app.strictmode.FragmentStrictMode
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
// Enforce FragmentStrictMode rules in debug builds
FragmentStrictMode.defaultPolicy = FragmentStrictMode.Policy.Builder()
.detectFragmentReuse()
.detectFragmentTagUsage()
.detectWrongFragmentContainer()
.penaltyLog()
.penaltyDeath() // Crash early in debug if rules are violated!
.build()
}
}Debugging Fragment Transactions via Logcat
# Filter FragmentManager backstack lifecycle state changes in Logcat
adb logcat -s FragmentManager:V
# Filter Fragment view lifecycle logs
adb logcat | grep -i "FragmentManager"
Comments and corrections