0

I want to check run-time permission inside a fragment. For Reference I followed This question. Permission Dialog is shown correctly but when I grant permission this exception occurs

java.lang.RuntimeException: Failure delivering result ResultInfo{who=@android:requestPermissions:, request=499835773, result=-1, data=Intent { act=android.content.pm.action.REQUEST_PERMISSIONS (has extras) }} to activity {com.test.myApp.dev/com.test.myApp.MyActivity}: java.lang.IndexOutOfBoundsException: Index: 499835773, Size: 5

This is my code in Fragment. For this I have used This Answer as reference

private var activityResultLauncher: ActivityResultLauncher<Array<String>>
init{
this.activityResultLauncher = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()) {result ->
        var allAreGranted = true
        for(b in result.values) {
            allAreGranted = allAreGranted && b
        }
        
        if(allAreGranted) {
          capturePhoto()            
        }
    }
}

// --- ---
 override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
// ... ... init views / binding... ...
   someBtn.setOnClickListener{
        val appPerms = arrayOf(
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA
        )
        activityResultLauncher.launch(appPerms)
  }       
}

Can someone tell me what I am doing wrong and how to rectify it.

Rahul Singh
  • 195
  • 2
  • 2
  • 13

1 Answers1

1

I don't actually know what happens but you can use another way like this:

  when{
                result[appPerms[0]] == false -> { 
                    //READ_EXTERNAL_STORAGE permission not granted
                    // Do something
                }

                result[appPerms[1]] == false -> {
                    //WRITE_EXTERNAL_STORAGE permission not granted
                    // Do something
                }

                result[appPerms[2]] == false -> {
                    //CAMERA permission not granted
                    // Do something
                }
                
                else -> {
                    //All permissions Granted
                    //Do something
                }
            }

put this code inside your activityResultLauncher