【问题标题】:lateinit property map has not been initializedlateinit 属性映射尚未初始化
【发布时间】:2020-12-20 09:09:08
【问题描述】:

最初我唯一的 Activity 是 MapsActivity ,带有以下 sn-p :

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

    private lateinit var map: GoogleMap

当我在 Java 源代码中创建 MainActivity 时,我这样调用 MapActivity:

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

但是现在,我得到 lateinit 属性映射尚未初始化

我尝试了 [这里][1] 的建议,但它说 lateinit 修饰符是不允许的 [1]:https://stackoverflow.com/questions/53076696/unable-to-initialize-googlemap-object-in-kotlin

【问题讨论】:

  • 你能准确地展示你尝试了什么吗?我认为private lateinit var mMap: GoogleMap? = null 会解决您的问题
  • @DavidKroukamp 您不能将 null 或任何值分配给 lateinit val/var
  • @padlanau 你能分享你的整个班级以及你想在哪里使用对象映射吗?
  • 如果是这种情况,那么 OP 应该简单地执行 private var map: GoogleMap? = null 并在使用 map 属性之前检查 null
  • lateinit 的重点是避免使事物可以为空,以便您以后可以初始化它们。 OP的问题是他们承诺在任何东西访问它之前初始化map,但是在它被设置之前有些东西正在读取它

标签: android google-maps kotlin


【解决方案1】:

这就是我初始化/固定地图的方式

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)
        }

【讨论】:

  • 我建议更换!!对于 ?.let 调用,这将防止您的应用在任何给定点崩溃
  • 谢谢@MahmoudOmara。我刚开始学习 Kotlin。
【解决方案2】:

为避免在使用 lateinit googleMap var 时出错,最好仅在已为其分配地图对象值时使用该 var。

【讨论】:

    【解决方案3】:

    您收到lateinit property map has not been initialized,因为该属性在被分配任何值之前已被读取。

    如果你不能确保它只有在你分配了任何值之后才会被使用,那么最好使用 private var map: GoogleMap? = null 并在阅读之前检查它是否为空。

    【讨论】:

      【解决方案4】:

      我遇到了类似的问题,因为我在回调方法中初始化之前尝试访问 Google 地图对象,

      所以我创建了一个带有布尔值的 livedata 对象,然后我在回调方法中将其设置为 true,然后我在 onViewCreated 上观察它,并且如果 livedata 对象具有值,则只会调用使用 googleMap 对象的方法是的。(我觉得可能有更好的方法)

      【讨论】:

        猜你喜欢
        • 2017-03-03
        • 1970-01-01
        • 2020-12-31
        • 2021-06-11
        • 2017-12-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多