The Tom
The Tom

Reputation: 15

lateinit property mMap has not been initialized

I wrote these lines of code and got error

Caused by: kotlin.UninitializedPropertyAccessException: lateinit property mMap has not been initialized

My method :

fun initCameraIdleListener() {
    var latitude = mMap.cameraPosition.target.latitude
    var longitude = mMap.cameraPosition.target.longitude
    myLatLng = LatLng(latitude, longitude)

    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(myLatLng, 18f))

}

Upvotes: 1

Views: 4998

Answers (2)

Mel
Mel

Reputation: 1820

This error is thrown when you declare a property as lateinit and don't initialize it before using it.

class YourClass {

    // You're declaring you'll assign a value for this field later in the code
    lateinit var someObject : SomeType

    fun doSomething(){
        someObject.method() // Boom ! UninitializedPropertyAccessException
    }
}

class YourClass {

    // You're declaring you'll assign a value for this field later in the code
    lateinit var someObject : SomeType

    fun doSomething(){
        someObject = SomeObject()
        someObject.method() // Totally fine !
    }
}

To avoid this error, you MUST initalize your property before trying to access it, else you'll always get this error.

If initializing it depends on a condition and you're not sure it happened or not, you can check by calling ::propertyName.isInitialized as @kartik malik suggested, before trying to use the property.

Upvotes: 2

Tiago Ornelas
Tiago Ornelas

Reputation: 1119

On the onMapReady callback you need to assign your propety to the argument received:

override fun onMapReady(googleMap: GoogleMap) {
   mMap = googleMap
   initCameraIdleListener()
}

only after this you can call initCameraIdleListener()

Upvotes: 2

Related Questions