I have a DialogFragment that should show from a parent fragment. After showing My DialogFragment, It will do seconds of work and dismiss the dialog.
Everything is OK, but when the screen rotates during its work, my app crashes on calling dialogFragment.dismiss() :
java.lang.IllegalStateException: Fragment MyDialogFragment ... not associated with a fragment manager.
Here is my code...
Parent Fragment :
class MyFragment: Fragment() {
...
fun showDialog(){
val dlg = MyDialogFragment()
dlg.show(childFragmentManager, "dlg")
MainScope().launch {
// Some time-consuming work...
delay(10000)
dlg.dismiss()
}
}
}
Dialog Fragment :
class MyDialogFragment : DialogFragment()
{
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return activity?.let {
val inflater = requireActivity().layoutInflater
val v=inflater.inflate(R.layout.my_dialog, null)
val builder = AlertDialog.Builder(it)
builder.setView(v)
.setTitle("title")
.setNegativeButton("cancel") { dialog, id ->
dialog?.cancel()
}
builder.create()
} ?: throw IllegalStateException("Activity cannot be null")
}
}
What I've tried :
using
dlg.retainInstance=true, will fix the problem but seems to be incorrect because of depreciation.using:
val d=childFragmentManager.findFragmentByTag("dlg") as MyDialogFragment
d.dismiss()
instead of dlg.dismiss(), That does not work and crashes with Fragment MyFragment ... has not been attached yet.