Manually override Fragments Auto Restoration

Fragment is the way to go for Android Development. However, for starter that learn Android Development, many might plagued with strange Fragment behavior that happens when the system restore the App.
Code as below definitely will have demonstrate strange behavior.
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
supportFragmentManager
.beginTransaction()
.replace(R.id.container, MainFragment())
.commit()
}}
For those experience in Android Development, we know the logic behind. It is simply because whenever the System Kills the App (that has Fragment in place), it will put the Fragment back in place automatically.
So with that, we should code in such a way, to create a new fragment IF AND ONLY IF when the App is NOT restored by the system (like code below), since the system will restore the fragment automatically.
class MainActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main) if (savedinstanceState == null) {
supportFragmentManager
.beginTransaction()
.replace(R.id.container, MainFragment())
.commit()
}
}
}The above is the simple part. Other than that, we also need to code within the Fragment itself too to handle restoration, and also if we have data model we need to saved and restore it etc.
So much to do 😓… can I skip that 🧐 ?
It is just too much to do if we’re writing a simple App that we don’t mind not restoring the Fragment by the system.
What we want is to whenever the system restore the App, just like starting the new App afresh. We don’t need to restore the state… just simple App that always restart if user terminate it, or when the system terminate it. No need state restoration!
Yes you can skip that 😊
Good news. That is possible, and very simple.
It just simply override the super.onCreate by passing in null instead of savedInstanceState.
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(null)
setContentView(R.layout.activity_main)
supportFragmentManager
.beginTransaction()
.replace(R.id.container, MainFragment())
.commit()
}}
That’s it.
With this, you need not worry about State Restoration, and the killed Fragment will not be restored automatically.
Disclaimer: I’m not advocating to use this for professional app development. This is not ideal, and only useful for specific case (where you want to have full control of the entire restoration manually) as well as a really simple App where restoration is not needed.
I hope this post is helpful to you. You could check out my other interesting topics here.
Follow me on medium, Twitter or Facebook for little tips and learning on Android, Kotlin etc related topics. ~Elye~






