https://kotlinlang.org logo
#android
Title
# android
s

stantronic

02/14/2020, 12:17 PM
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

gian

02/14/2020, 12:23 PM
I think the synthetic property will be null when the view is destroyed
s

stantronic

02/14/2020, 12:28 PM
Maybe. But then why would it be destroyed, if the call is from a dialog displaying on that screen?
b

bezrukov

02/14/2020, 12:47 PM
Because dialog has different lifecycle than fragment - it attached directly to window
s

stantronic

02/14/2020, 2:40 PM
ah, good to know, thanks
i

itnoles

02/14/2020, 5:11 PM
On Kotlin Bytecode, the syntheic property will be NULL when onDestroyView occurred.
in Fragment
s

stantronic

02/14/2020, 5:14 PM
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

itnoles

02/14/2020, 5:20 PM
Fragment is not completely destroyed when the onDestroyView occurred. https://www.javatpoint.com/android-fragments
s

stantronic

02/14/2020, 5:46 PM
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

bezrukov

02/14/2020, 6:00 PM
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

zhuinden

02/17/2020, 11:18 PM
You should check
isAdded()
before you do anything with the Fragment. If it is
!isAdded()
then consume the method call
s

stantronic

02/18/2020, 9:22 AM
Thanks guys, appreciate the help 🙂