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

Saiedmomen

12/12/2018, 11:48 AM
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

Rohan Maity

12/13/2018, 12:33 AM
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

Saiedmomen

12/13/2018, 7:39 AM
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

Rohan Maity

12/14/2018, 5:13 AM
Are you saying you are getting null in onViewCreated ?
s

Saiedmomen

12/14/2018, 10:18 AM
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

Rohan Maity

12/14/2018, 12:05 PM
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

Saiedmomen

12/14/2018, 6:37 PM
very intresting. so you mean
findCachedViewById
wouldn't initialize while resumed?
r

Rohan Maity

12/15/2018, 8:00 AM
It would initialize in onResume() as view is just resumed . But not in running state of UI
s

Saiedmomen

12/16/2018, 6:02 PM
Awesome thank you!
16 Views