How do you handle properties that are initialized ...
# android
s
How do you handle properties that are initialized in the onCreate of an Android Service? Do you make them lateinit or nullable? We have them lateinit and we now had an "UninitializedPropertyAccessException" where a variable was accessed in onDestroy but onCreate had not been called before. I did not know that was possible. Now we either make all the variables nullable which adds a lot of null checks or we check "this::variable.isInitialized" which is also not nice style. How do you handle it?
f
Very interesting! I also didn’t know it was possible for onDestroy to be called before onCreate. I guess I would leave them as lateinit; And everywhere assume they are initialized. Except for in the onDestroy, and do the this::variable.isInitialized there. Not nice indeed. But what else can you do. 🤷
c
I would rather question if that just was a glitch in the Matrix 😉 Did you actually init it in
onCreate
? Do you have it reproducible? Which Android Version? Which device? The Service’s lifecycle needs
onCreate
before
onDestroy
is called.
Also how do you start the service?
And to answer your actual question: We built dozens of services and since Kotlin is around, we use
lateinit
for those kind of properties. If its an
Activity
, a
Service
or a
BroadcastReceiver
, no matter, we never had issues with that.
s
The service is started by another Service via bindService. The crash happened one time during an automated test run. I don't know how it happened and I cannot reproduce it.
The Android Version was 13. It is an AOSP project, with some system changes but we are not a system service.
c
If you cannot reproduce it, I’d ignore it for now 🤷
m
Another option is to move the logic out of the service and into another class that you can initialize in
onCreate
and cleanup in
onDestroy
make that class nullable, and the only null checks are in the service and no lateinits.