0

Hello I'm having an error when passing the same value from if to else the logcat doesn't give me more information just E / AndroidRuntime: FATAL EXCEPTION: main, and points the line that contains the if and the else. could someone tell me how to fix it? any help is welcome.

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)


    }

1 Answers1

1

You are using not-null assertion operator which will throw NPL if any of the value is null so your currentLocation is null which is throwing the exception.

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

here if the currentLocation is null then you are still using it inside else case which is clearly the root cause of exception (thrown by !!)

Either use dummy value(preferably fix the issue with currentLocation) or you can use safe call with let as .?let

currentLocation?.let{ // run if currentLocation is not null
    val position = LatLng(it.latitude, it.longitude)
    //... code 
}
Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68
  • Hello, you could include in the answer how this line of code would be complete with the alternative you informed, thanks sorry to bother you. I'm a beginner –  Mar 02 '20 at 16:13
  • @YPLABS you need to fix `currentLocation` initialisation which is a different issue as using dummy location is an option for latlong but it's not a desired behaviour. `if (currentLocation != null) LatLng(currentLocation!!.latitude, currentLocation!!.longitude) else LatLng(25.2744, 133.7751)/* dummy values*/` – Pavneet_Singh Mar 02 '20 at 16:17
  • yes but I need to pass the same value from the if to the else to both take the current location –  Mar 02 '20 at 16:25
  • @YPLABS you can use dummy values in `else` statement as shown in previous comment or you can use [getLastKnownLocation](https://stackoverflow.com/a/9873351/4936904) – Pavneet_Singh Mar 02 '20 at 16:29