thovor
thovor

Reputation: 3

Uninitialized exception while initializing "late init" property

I am not really sure if my case is just not possible with late init properties. But let me just ask :)

I have an applicationController which is used in nearly every activity - so i created a BaseActivity

The problem now is that when I want to get dependencies from the application controller in the child activity, I get an Uninitialized Exception.

Thanks for your help!

Upvotes: 0

Views: 310

Answers (1)

Son Truong
Son Truong

Reputation: 14193

Because you override wrong method in BaseActivity, that why your app crash.

Solution: Change your code to

abstract class BaseActivity : AppCompatActivity() {

    lateinit var applicationController: ApplicationController

    // [IMPORTANT] Remove or comment-out this method
//    override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
//        super.onCreate(savedInstanceState, persistentState)
//        applicationController = ApplicationController.getInstance(applicationContext)
//    }

    // Override this method
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        applicationController = ApplicationController.getInstance(applicationContext)
    }
}

Explanation: This section will explain why the code is not working.

kotlin.UninitializedPropertyAccessException

This is a sub-class of RuntimeException, the app will throw this exception when you access an object by calling properties or methods on its own before initializing.

When LoginScreen activity is created, Android will call its onCreate method.

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    setContentView(R.layout.activity_login_screen)

    emailMatcher = applicationController.getEmailMatcher()
    passwordMatcher = applicationController.getPasswordMatcher()
}

The first line super.onCreate(savedInstanceState) will call onCreate method of its parent, in this case onCreate (bundle) in BaseActivity activity will be called.

Unfortunately, in BaseActivity activity, you override and put the initial code for applicationController in another method onCreate(bundle, persistentState) which quite similar to onCreate (bundle). The difference between them is number of params. As a result, at this time applicationController is still not initialized.

override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
    super.onCreate(savedInstanceState, persistentState)
    applicationController = ApplicationController.getInstance(applicationContext)
}

Until the app reach this line

emailMatcher = applicationController.getEmailMatcher()

Because you call getEmailMatcher method on an uninitialized object applicationController, so the app throws kotlin.UninitializedPropertyAccessException and make your app crash.

Upvotes: 4

Related Questions