[Deprecated] Kotlin extensions to commit Fragments safely 😎
Use the official
FragmentManager
extension to manage fragments: https://developer.android.com/guide/fragments/transactions
Since fragments appeared in Android, many developers have criticized this component. The main reasons to not recommend fragments in android are; complex lifecycle, hard to debug and easy to lose the fragment state.
Regarding this last reason, how many of you have seen this exception in your implementations?
java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1341)
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1352)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:595)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:574)
The goal of this post is to show you a way to prevent the state loss fragment exception using kotlin extensions and android support library (version up to 26.0.0).
Why is this exception thrown? 🤔
If you don’t know why this exception is thrown, I strongly recommend you to read the Fragment Transactions & Activity State Loss article from @alexjlockwood, in which he explains it in great detail.
Android Support Library
Since version 26.0.0-beta 1 we can check in your app if fragments can be committed to allow the state loss or not.
FragmentManager
andFragment
have anisStateSaved()
method to allow querying whether or not a transaction will be allowed without state loss. This is especially useful to check when handling anonClick()
event before executing any transaction.
As you can see, the isStateSaved()
method is really useful in order to avoid unexpected scenarios.
Kotlin extensions
Kotlin Android Extensions can be really useful to improve support for Android development. Extensions provides the ability to extend a class with new functionality without having to inherit from the class or use any type of design pattern. Kotlin supports extension functions and extension properties.
How to combine both?
Well, it’s not rocket science. In the following example you can see how an activity extension can commit a fragment in a safe way using isStateSaved method from the android support library:
Then, it can be invoked directly from any activity that extends from AppCompatActivity:
Github example
I’ve created a simple project example on Github 😊
https://github.com/mgarciaguerrero/safe-android-fragments
That’s all folks, I hope it has been helpful for you 🖖