Is it bad practice to use Global variables instead of bundles to preserve state between screen rotations?
I really like just using global variables to keep state. But since everything suggests using bundles, should I do that? I don’t know what pitfalls I could be thinking of.
Here is a snippet of code that demonstrates global variables dont change.
I have to check that the LEVEL_DEFS list is 0 before adding to it, otherwise every screen rotation adds duplicate levels (where I originally assumed I would have to re-add the levels after rotation)
`
val LEVEL_FILES = arrayOf("levels/lv1.txt", "levels/lv2.txt", "levels/lv3.txt")
val LEVEL_DEFS = mutableListOf<LevelDefinition>()
fun getAllLevels(context: Context): MutableList<Level> {
if (LEVEL_DEFS.size == 0) {
for (filename in LEVEL_FILES) {
LEVEL_DEFS.add(LevelDefinition(getTextFileString(context, filename)))
}
}
}
`
When I google screen rotation, all the results suggest that you have to use a bundle to save state.
I also asked chat gpt-3, which insisted that I must use a bundle to save the state during rotation.
Yet, it is clear to me that global variables do not change during rotation. I have used many simulated and real devices and they all behave the same way.
>Solution :
Global variables persist as long as your application is running – however when it is in the background you have no guarantee that the Android OS won’t stop and re-start your application (which would lose any global or static variables). Once your application goes to the background, you can no longer be certain they will stick around.
What you have posted looks like it would be fine though if you only access it through the getAllLevels method (since it re-creates it when needed). However, if you are adding levels somewhere else, those could be lost.
If you want to be able to add levels, one possible solution would be to load the data from SharedPreferences inside getAllLevels when the list is empty – and update the SharedPreferences any time levels are added.