Android Studio stopped generating the preview of my layout. The problem is caused by the presence of custom views.
The error :
Render Problem
java.lang.NullPointerException at
com.my.app.views.bars.TopBar$mainViewModel$2.invoke(TopBar.kt:26) at
com.my.app.views.bars.TopBar$mainViewModel$2.invoke(TopBar.kt:25) at
layoutlib.internal.kotlin.SynchronizedLazyImpl.getValue(LazyJVM.kt:74)
The problem seems to come from the ViewModelProvider :
private val mainViewModel by lazy {
ViewModelProvider(findViewTreeViewModelStoreOwner()!!).get<MainViewModel>()
}
Similar Posts :
Kotlin delegate property causes a preview rendering error in Android Studio
Custom View does not render in Design View in Android Studio?
2
Answers
Android Studio can't generate the preview of a custom view that uses a ViewModelProvider. However we can prevent it from crashing by checking if it is in "Edit Mode" before drawing the view.
Please note that this must be done inside the "OnDraw" method.
Indeed, replacing the mainViewModel with NULL isn't an option, because it can and will lead to NullPointerExceptions.
You are facing NPE because when your custom view is in edit mode (which is the case when it’s rendered in preview), then there’s no proper view tree owner and you get
null
back. You can check that by using isInEditMode():