androidkotlininitializationkotlin-lateinit

lateinit property instance has not been initialized, while making an app


I'm a new developer(If I can call myself one) making an alarm app. I think I made other parts of the app but however hard I try, I can't find out how to fix the error. To access instance in AlarmManager.kt, I can't help but make instance companion object. But I guess that makes the problem.... Please could anyone tell me how can I fix this error? Thanks in advance!

kotlin.UninitializedPropertyAccessException: lateinit property instance has not been initialized

↓ SampleApplication.kt

class SampleApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        instance = this
    }

    companion object {
        lateinit var instance: SampleApplication private set
    }
}

↓AlarmManager.kt

object AlarmManager {
    var mService: MusicService? = null
    lateinit var mediaPlayer: MediaPlayer
    lateinit var mView: View
    lateinit var mTimer: Timer
    val tag1 = "alarm1"
    val tag2 = "alarm2"
    private val windowManager: WindowManager by lazy {
        SampleApplication.instance.getSystemService(Context.WINDOW_SERVICE) as WindowManager
    }

Solution

  • You would need to register SampleApplication in AndroidManifest file. Then only it will executed as an application class

    <application
        android:name=".SampleApplication">