0

I'm trying to get actual location. I readed and tried dozens of examples. But all ends with error.

Example: val locationManager = context.getSystemService(LOCATION_SERVICE) as LocationManager

Ends with this error: Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type Context?

Or I tried this. But ActivityCompat and content are red in Android studio.

I tried xx versions but some error was always there.

I'm creating GPS tracker. I'm starting with simple location detection.

Do you know some example for Android studio 4.1.2?

1 Answers1

0
Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type Context?

This means that the variable context is of a Kotlin nullable type. In Kotlin, unlike Java, you need to specify whether a variable can be null or not. Accessing such a variable is done through the syntax variable?.method() to signify that you understand that the call may evaluate to null.

So in your example, it would look like:

val locationManager = context?.getSystemService(LOCATION_SERVICE) as? LocationManager

Since locationManager was assigned a nullable type, it is now also nullable. You could mitigate this by doing something like:

val locationManager = (context?.getSystemService(LOCATION_SERVICE) as? LocationManager) ?: error("Could not get LocationManager")
omiwrench
  • 90
  • 1
  • 9
  • Understand. It works, thanks! But how to get details from `locationManager` variable? I'm trying `getLatitude()` or `getLongitude()` - without success . –  Jan 20 '21 at 16:41
  • https://stuff.mit.edu/afs/sipb/project/android/docs/training/basics/location/locationmanager.html https://www.codota.com/code/java/how-to/finding-current-android-device-location – Dmitry Jan 21 '21 at 14:17
  • 1
    Thanks! After hours and hours it works! I'm excited from Kotlin. –  Jan 23 '21 at 15:45