【问题标题】:E/AndroidRuntime: FATAL EXCEPTION: main Kotlin no error details in logocatE/AndroidRuntime: FATAL EXCEPTION: main Kotlin no error details in logocat
【发布时间】:2020-03-02 15:52:53
【问题描述】:

您好,当将相同的值从 if 传递给 else 时出现错误,logcat 没有给我更多信息,只是 E / AndroidRuntime: FATAL EXCEPTION: main,并指向包含 if 和 else 的行。有人可以告诉我如何解决吗?欢迎任何帮助。

override fun onMapReady(googleMap: GoogleMap) {
        Log.i("MAP READY", "READY")
      LINE ERROR  val position = if (currentLocation != null) LatLng(currentLocation!!.latitude, currentLocation!!.longitude) else  LatLng(currentLocation!!.latitude, currentLocation!!.longitude)
        this.map = googleMap
        this.map!!.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 15f)) // Vienna
        getFineLocationPermission()
        this.map!!.setOnMarkerClickListener(this)
        this.map!!.uiSettings.isRotateGesturesEnabled = true
        this.map!!.uiSettings.isZoomGesturesEnabled = true
        this.map!!.setOnInfoWindowClickListener(this)
        this.map!!.setOnMapLongClickListener(this)


    }

【问题讨论】:

    标签: android android-studio kotlin


    【解决方案1】:

    您正在使用not-null assertion operator,如果其中任何一个值为 null,则将引发 NPL,因此您的 currentLocation 为 null,这将引发异常。

    val position = if (currentLocation != null) LatLng(currentLocation!!.latitude, currentLocation!!.longitude) else  LatLng(currentLocation!!.latitude, currentLocation!!.longitude)
    

    如果currentLocation 为空,那么您仍在else 情况下使用它,这显然是异常的根本原因(由!! 抛出)

    要么使用虚拟值(最好解决 currentLocation 的问题),或者您可以使用 let 作为 .?let 的安全调用

    currentLocation?.let{ // run if currentLocation is not null
        val position = LatLng(it.latitude, it.longitude)
        //... code 
    }
    

    【讨论】:

    • 您好,您可以在答案中包含这行代码将如何与您告知的替代方案一起完成,谢谢打扰您。我是初学者
    • @YPLABS 您需要修复 currentLocation 初始化,这是一个不同的问题,因为使用虚拟位置是 latlong 的一个选项,但这不是所需的行为。 if (currentLocation != null) LatLng(currentLocation!!.latitude, currentLocation!!.longitude) else LatLng(25.2744, 133.7751)/* dummy values*/
    • 是的,但我需要将相同的值从 if 传递给 else 以获取当前位置
    • @YPLABS 您可以在else 语句中使用虚拟值,如之前的评论所示,或者您可以使用getLastKnownLocation
    猜你喜欢
    • 2017-02-18
    • 2019-05-19
    • 1970-01-01
    • 1970-01-01
    • 2016-07-14
    • 2020-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多