Skip to content

PreferenceFragmentCompat

Published: April 25, 2019

2 min read

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 this 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, weird!

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 intervention.

Somewhere on the StackOverflow, I found out that the Bundle i.e. the savedInstanceState variable is "NULLABLE".

The automated refactor somehow 'missed' to put an ? to Bundle object, hence making it @NonNull which caused the crash. If that's happened or is happening to you, just mark the Bundle as well as the RootKey as Nullable as –

kotlin
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {}

Darshan Pandya