I sometimes get null from "Kotlin android extensio...
# android
s
I sometimes get null from "Kotlin android extensions synthetic binding" although the view is created and in resumed state. Weird thing is if I access the binding in
onViewCreated
with an empty
apply
the binding works properly. Here is a question I asked on stackoverflow when I first encountered the issue https://stackoverflow.com/questions/48971322/kotlin-android-extension-fragment-view-null Has anyone else experieced this issue?
r
contentView which you are referring to with Kotlin synthetic extensions, it just gives you the reference to view object (in your case content View). If you access this object before layout or view is created , it will return null Now in Fragment. , It is in the onViewCreated() where your view is created (build or initialized) . So is your contentView is created (is initialized)
🔥 1
s
yeah I understand that. The view is created and fragment is resumed. so onViewCreated is run and the binding shouldn't really be null
r
Are you saying you are getting null in onViewCreated ?
s
Its such a weird error. The binding is null it in the callback of an async task which was initiated in onViewCreated. So defeinitely after that
line 47: start of task line 55: where error happens line 34: the fix
r
Ok kotlin Synthetic binding internally works this way It calls .findCachedViewById() this is different from .findViewById(). When .findCachedViewById() is first time called , it reads all ids form XML , creates ids objects(view) and store them in HashMap() or HashTable() . So when you call . findCachedViewById() (Kotlin synthetic) next time it returns value from the HashMap() unlike findViewById() which reads XML every time you call it. Here comes your case when do roptView.apply{}, then findCachedViewById() firsts sees the HashMap() . If there is no HashMap() then it firsts create HashMap() by reading XML and returns object(view) But when you simply pass rootView in the SnackBar. It's already in resume state (UI visible to user) it tries to get view by .findCachedViewById() in that (UI visible) state . But this time it finds no HashMap() (as this is the first call to . findCachedViewById) also this is in UI state so reading XML is heavy task. Therefore . findCachedViewById () returns null Hence your rootView is null by Synthetic binding
s
very intresting. so you mean
findCachedViewById
wouldn't initialize while resumed?
r
It would initialize in onResume() as view is just resumed . But not in running state of UI
s
Awesome thank you!