0

Problem:

I have done this LocationPermission task with activity but I want to do it with the fragment. In Fragment method onRequestPermissionsResult() is not being called.

There are many answers to this question but unfortunately non of them worked for me. Some of those answers are in java which is not applicable in kotlin, for instance, one answer says using 'FragmentCompat' this problem can be solved but we don't have FragmentCompat in Kotlin.

What I did so far?

I followed this question and many others.

Before ActivityCompat.requestPermissions(requireActivity(), arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 1)

After: requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),1)

though requestPermissions is depricated But nothing worked so far.

PLEASE DO CONSIDER KOTLIN LANGUAGE FOR ANSWERS

Code in Fragment:

fun RequestLocationPermission()
    {
        Log.d(TAG, "RequestLocationPermission: ")
        if(ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
        {
            if(ActivityCompat.shouldShowRequestPermissionRationale(requireActivity(), Manifest.permission.ACCESS_FINE_LOCATION)){
                requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),1)
            }
            else{
                ActivityCompat.requestPermissions(requireActivity(), arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 1)
                requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),1)
            }
        }
    }
 override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        Toast.makeText(requireContext(), "Request Permission Called", Toast.LENGTH_SHORT).show()
        Log.d(TAG, "onRequestPermissionResult Called ")

        when (requestCode) {
            1 -> when {
                grantResults.isEmpty() ->
                    // If user interaction was interrupted, the permission request
                    // is cancelled and you receive empty arrays.
                    Log.d(TAG, "User interaction was cancelled.")
                grantResults[0] == PackageManager.PERMISSION_GRANTED ->{
                    // Permission was granted.
                    locationPermission = true
                    fetchLocation()

                }
                    else -> {
                    // Permission denied.
                    Toast.makeText(requireContext(), "Permission Denied", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

0 Answers0