[ad_1]
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.
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 “Granted” without showing the popup.
Here is my code in DialogFragment:
class SaveCalibrationDialogFragment(val data: String) : DialogFragment() {
private val activityResultLauncher = registerForActivityResult(
ActivityResultContracts.RequestPermission()) { isGranted ->
println("Received CallBack")
if (isGranted) {
println("Permission granted!")
} else {
println("Permission needed!")
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val builder = AlertDialog.Builder(this.requireContext())
val dialog = builder.setTitle("Notice")
.setMessage("Data is not saved. Do you want to save before exiting?")
.setNegativeButton("No") { dialog, _ ->
}.setPositiveButton("Yes") { _, _ ->
activityResultLauncher?.launch(WRITE_EXTERNAL_STORAGE)
}
.create()
return dialog
}
}
Activity:
cancel.setOnClickListener {
if (viewModel.isDataSave && viewModel.isLastPage) {
setResult(Activity.RESULT_OK, intent)
finish()
} else if (!viewModel.isDataSave && viewModel.isLastPage){
SaveCalibrationDialogFragment(viewModel.dataToSave!!).show(this.supportFragmentManager, "costumeSaveDialog")
} else {
setResult(Activity.RESULT_CANCELED, intent)
finish()
}
}
[ad_2]