0

I'm using DialogFragment and in the onCreateDialog I need to use the Activity's reference. The issue is that with the latest support library (28.0.0), the activity becomes nullable, so when using AlertDialog.Builder in onCreateDialog I'm forced to use !!

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
    [...]
    val dialog = AlertDialog.Builder(activity!!).setTitle(R.string.title)[...].create()
    [...]
    return dialog
}

I can't add any null check because I need to return a dialog anyway. Is there any clean solution to avoid to use !! operator?

A._
  • 23
  • 6

1 Answers1

0

Use requireActivity() but bear in mind that if your fragment is not yet bound to an activity it will throw an IllegalStateException

92AlanC
  • 1,327
  • 2
  • 14
  • 33
  • Note that the framework will never call `onCreateDialog()` on a detached fragment. As long as you're not crazy enough to call it yourself, you should be fine. – Nitrodon Apr 22 '20 at 16:09
  • Exactly. There are some edge cases (quite rare to be fair) when it may happen but nothing to be paranoid about – 92AlanC Apr 22 '20 at 16:12