Why does FusedLocationProviderClient.getCurrentLocation() always return a null object?

3.1k Views Asked by At

I am trying to get the location whenever a user clicks a button. I have the code below but the outcome of "location" always is null. I am running this on an emulator in Android Studio and whenever I check out the app info, location services are turned on and location permission is successfully granted. So why can I not pull valid locations?

val location_button = view.findViewById<ImageButton>(R.id.get_location)
location_button.setOnClickListener {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(requireActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_DENIED || ContextCompat.checkSelfPermission(requireActivity(), android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_DENIED) {
            val permission = arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION)
            requestPermissions(permission, LOC_PERMISSION_CODE)
        }
        else {
            //permission already granted
            val priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY
            val cancellationTokenSource = CancellationTokenSource()

            fusedLocationClient.getCurrentLocation(priority, cancellationTokenSource.token)
                .addOnSuccessListener { location ->
                    println("location is found: $location")
                }
                .addOnFailureListener { exception ->
                    println("LOCATION NOT FOUND")
                }
        }
    }
    else {
        val priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY
        val cancellationTokenSource = CancellationTokenSource()

        fusedLocationClient.getCurrentLocation(priority, cancellationTokenSource.token)
            .addOnSuccessListener { location ->
                println("location is found: $location")
            }
            .addOnFailureListener { exception ->
                println("LOCATION NOT FOUND")
            }
    }
}
0

There are 0 best solutions below