Noticing a few crashes in our app caused by NPEs ...
# android
s
Noticing a few crashes in our app caused by NPEs - the pattern seems to be when an alert dialog calls a success lambda which then calls a method in a fragment which performs some action on a kotlin synthetic property view. Has anybody faced anything similar? I’m struggling to work out whether its because of lifecycle issues, or the way lambdas work, or the way synthetic properties work, or all of the above.
g
I think the synthetic property will be null when the view is destroyed
s
Maybe. But then why would it be destroyed, if the call is from a dialog displaying on that screen?
b
Because dialog has different lifecycle than fragment - it attached directly to window
s
ah, good to know, thanks
i
On Kotlin Bytecode, the syntheic property will be NULL when onDestroyView occurred.
in Fragment
s
I still dont understand why the fragment would be destroyed if the alert dialog is showing on top of it. Surely it should only be in a paused state?
i
Fragment is not completely destroyed when the onDestroyView occurred. https://www.javatpoint.com/android-fragments
s
So can destroy view get called when an alert dialog fragment is displaying on top of it? That is counter-intuitive, as the view is still partially visible
b
Alert doesn't know anything about your fragment 🙂 you're passing a context (Activity) to AlertDialog, so it knows only about your Activity. So alert will be displayed even if you remove a fragment from fm
Probably DialogFragment is what you want - you can add it to childFragmentManager of your fragment, then it will follow the lifecycle of it
👍🏻 1
Another option is to implement your own extension of displaying alert dialog which takes Fragment's Lifecycle and use it to show/hide/dismiss alert in onStart/onStop/onDestroy
z
You should check
isAdded()
before you do anything with the Fragment. If it is
!isAdded()
then consume the method call
s
Thanks guys, appreciate the help 🙂