Save and Restore Instance States in Kotlin

Cotton balls next to linen napkin

When you rotate an Apple device, the internal state is maintained. When you rotate an Android device, however, the internal state is reset. To create the illusion of continuity, the developer needs to save the state before rotation, and restore the state after. That's not difficult to do, as Android provides two aptly named overrides: onSaveInstanceState() and onRestoreInstanceState(). But this does introduce a wrinkle in how to maintain design portability between the two platforms. How many other hidden differences might there be?

Exploring the overrides, I found various helper functions to put and get native types such as boolean, int, double, strings, and more. The values are assigned to a key in the form of a string label. The code fragments below -- extracted from my app LuldCalc -- show examples, with special handling for enumerations because they are classes in Kotlin. Since I can't put a class object, I extract the ordinal value -- an int -- and save that instead. Similarly, when I get the ordinal value, I translate it to the desired enum. 

enum class Operation {
Add, Subtract, Multiply, Divide,

override fun onSaveInstanceState(outState: Bundle) {


outState.putString("refPriceLabelStrState", refPriceLabelStr)
outState.putBoolean ("clearFlagState", clearFlag)
outState.putInt("opKeyOrdinalState", opKey.ordinal)
"refPriceState", refPrice)
override fun onRestoreInstanceState(savedInstanceState: Bundle) {

clearFlag = savedInstanceState.getBoolean("clearFlagState")

val opKeyOrdinal: Int = savedInstanceState.getInt("opKeyOrdinalState")
when (opKeyOrdinal)
0 -> opKey = Operation.None
1 -> opKey = Operation.Add
2 -> opKey = Operation.Subtract
3 -> opKey = Operation.Multiply
4 -> opKey = Operation.Divide
5 -> opKey = Operation.Equal

refPrice = savedInstanceState.getDouble("refPriceState")
refPriceLabelStr = savedInstanceState.getString("refPriceLabelStrState")!!
It all works nicely enough, but would I have been better off simply defining opKey as a char and use the putChar() and getChar() methods? While enumerations provide clarity, they require extra code to manage device rotation... at least under Android. With iOS, rotation is handled automatically, and I am free to use enumerations without penalty.

Having one code base for both iOS and Android is impractical, so I strive to have the apps share a common design and structure. But as illustrated here, even that is a challenge. If there are Kotlin experts reading this, is there a better way to save and restore instance states for enumerations?


Popular posts from this blog

Bookshelf: UNIX A History and a Memoir

Bookshelf Classic: The C Programming Language