title: Request permission to write in DialogFragment with new registerForActivityResult
body: <p>I try to remind the user to save the data in a file when exiting the activity. So I show a dialog asking if they want to store the data. Here I need to check if the permission is granted or not. If not, request it and as soon as it is granted, write to file.</p>
  <p>I had trouble catching the onRequestPermissionResult call back in my DialogFragment so I started using the new registerForActivityResult. The problem is that when the permission is not yet granted the popup appears to request permission but when the permission is granted then call back is not called. If I press close button again then it check the permission and the call back now receives &quot;Granted&quot; without showing the popup.</p>
  <p>Here is my code in DialogFragment:</p>
  <pre><code>class SaveCalibrationDialogFragment(val data: String) : DialogFragment() {
      private val activityResultLauncher = registerForActivityResult(
          ActivityResultContracts.RequestPermission()) { isGranted -&gt;
          println(&quot;Received CallBack&quot;)
          if (isGranted) {
              println(&quot;Permission granted!&quot;)
          } else {
              println(&quot;Permission needed!&quot;)
          }
      }
  
      override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
          val builder = AlertDialog.Builder(this.requireContext())
          val dialog = builder.setTitle(&quot;Notice&quot;)
              .setMessage(&quot;Data is not saved. Do you want to save before exiting?&quot;)
              .setNegativeButton(&quot;No&quot;) { dialog, _ -&gt;
              }.setPositiveButton(&quot;Yes&quot;) { _, _ -&gt;
                  activityResultLauncher?.launch(WRITE_EXTERNAL_STORAGE)
              }
              .create()
          return dialog
      }
  
  }
  </code></pre>
  <p>Activity:</p>
  <pre><code>cancel.setOnClickListener {
          if (viewModel.isDataSave &amp;&amp; viewModel.isLastPage) {
              setResult(Activity.RESULT_OK, intent)
              finish()
          } else if (!viewModel.isDataSave &amp;&amp; viewModel.isLastPage){
              SaveCalibrationDialogFragment(viewModel.dataToSave!!).show(this.supportFragmentManager, &quot;costumeSaveDialog&quot;)
          } else {
              setResult(Activity.RESULT_CANCELED, intent)
              finish()
          }
  
      }
  </code></pre>