PreferenceFragmentCompat

Recently, while migrating one of my App ‘InSaver!’ from Java to Kotlin, I stumbled upon a strange, like very strange issue.. 😕

I had a SettingsActivity and a SettingsFragment nested in the same Activity which extended PreferenceFragmentCompat.

Everything was just Fine in Java & then just a quick Convert to Kotlin took so many hours to get fixed!

So, what was all the ruckus about?
Well my SettingsFragment crashed as soon as it hit the onCreatePreferences() method..
The only thing that logcat showed was that the Bundle in the constructor i.e. savedInstanceState was null 🙄.

This shouldn’t have happened because I used the built-in Refactor to convert Java to Kotlin as this class had nothing much which needed my manual interaction..

Finally…
Somewhere on the stackoverflow, I found out that the Bundle i.e the savedInstanceState variable is “NULLABLE”.

The automated refactor somehow ‘forgot’ or maybe it was an other issue.. I don’t know that yet, to put an ? to Bundle object, hence making it @NonNull which made Kotlin fire the crash..

If that’s happened or is happening to you, just mark the Bundle as well as the RootKey as Nullable like –

override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {}
Posted in Blog

Write a comment