0
votes

I have a variable in my fragment class:

private lateinit var dManager: DataManager

And I'm initializing it before the first using here:

override fun onResume() {
    super.onResume()
    dManager = MyApp.gManager.getDataManager(sp,level,test)
    if (dManager.hp< 1) { 
       ...
       ...
       ...
    }
}

This code works ok for me and most users (99.5%), but sometimes i get crash report

lateinit property dManager has not been initialized

How can this happen? What should I do to prevent it?

2
Guess it means that MyApp.gManager.getDataManager returns null. Why can this happen? Well, that depends on how you're initializing it O_oEpicPandaForce
@EpicPandaForce You'd get a different error message in this case, I believe. I'd look for other uses of dManager instead and if they can ever happen before onResume.Alexey Romanov

2 Answers

1
votes

lateinit var makes compiler aware that’s not null

  1. If your property is lifecycle-driven (e.g. a reference to a TextView or ImageView which gets inflated during Android Activity lifecycle) or it is initialized through injection, you cannot supply a non-null initializer and you must declare its type as nullable. This in turn will require you to use null checks every time you reference the property, which may be a bit inconvenient, especially if you are absolutely sure the property will get initialized at some point, before you access it for the first time.
  2. Kotlin has a simple solution for such a scenario, allowing you to mark the property with the lateinit modifier.
  3. If you access the property before initialization, you’ll get an UninitializedPropertyAccessException.

getDataManager(sp,level,test) may return sometimes null so for safe sides your solution would be like as :-

override fun onResume() {
super.onResume()
dManager = MyApp.gManager.getDataManager(sp,level,test)
if (::dbManager.isInitialized && dManager.hp< 1) { 
   ...
   ...
   ...
}
}
0
votes

May be your getDataManager(sp,level,test) return null value

OR

As per the document you have to check object with .isInitialized property.

Returns true if this lateinit property has been assigned a value, and false otherwise.

Check lateinit var is initialized

lateinit var file: File    

if (::file.isInitialized) { ... }