I am working with the Kotlin language in android studio. I am requesting permission to access the gallery and I am writing this when I use the "if-else" structure to query the permission and there is a dash above the requestPermissions statement. how do we solve this.
activity?.let {
if (ContextCompat.checkSelfPermission(requireActivity().applicationContext,Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1)
The new approach to request permissions is to use launchers. You have to create the launchers before setContent().
At the very top before onCreate, create a launcher property:
val storagePermissionLauncher = registerForActivityResult(ActivityResultContracts.startActivityForResult())
{ result->
if(result.RESULT_CODE == RESULT_OK) {
//permission granted
doSomething()
}
}
When you have to do something that requires a permission. You have to check if you have the permission:
if(ContextCompat.checkSelfPermission(context, android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){
//you have the permission
doSomething()
}else{
//You don't have the permission, ask for it.
storagePermissionLauncher.launch(android.Manifest.permission.READ_EXTERNAL_STORAGE)
}