简体   繁体   中英

lateinit property map has not been initialized

Initially the only Activity I have is MapsActivity with the following snippet:

class MapsActivity : AppCompatActivity(), OnMapReadyCallback, GoogleMap.OnMarkerClickListener {

    private lateinit var map: GoogleMap

When I created a MainActivity in Java source codes, I called the MapActivity like this:

Intent i = new Intent(getApplicationContext(), MapsActivity.class);
                    startActivity(i);

But now, I am getting lateinit property map has not been initialized

I tried what was advised [here][1] but it says lateinit modifier is not allowed [1]: https://stackoverflow.com/questions/53076696/unable-to-initialize-googlemap-object-in-kotlin

This is how I initialized/fixed map

private lateinit var map: GoogleMap
private val SYDNEY = LatLng(-33.87365, 151.20689)
.
.
override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_maps)
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment?
        mapFragment!!.getMapAsync { googleMap ->
            map = googleMap
            marker = googleMap.addMarker(MarkerOptions().title("Sydney").position(SYDNEY))
            googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(SYDNEY, 15f))
            googleMap.animateCamera(CameraUpdateFactory.zoomTo(10f), 2000, null)
        }

to avoid errors when using the lateinit googleMap var, best to only use the var when the map object value has been assigned to it.

You are getting lateinit property map has not been initialized because that property it's being read before it has been assigned any value.

If you can't ensure that it will be used only after you have assigned any value, then it's better to use a private var map: GoogleMap? = null private var map: GoogleMap? = null and check if that's null before reading it.

I was facing a similar issue because I was trying to access a Google map object before it was initialized in the callback method,

so I created a livedata object with a boolean value, which I then set to true in the callback method, then I observed it in on onViewCreated and would only call the method that was using the googleMap object if the livedata object has value true.(I feel like there might be a better way of doing this)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM