Search code examples
android-studiokotlinandroid-custom-viewpreview

How to generate the preview of a custom view that uses a ViewModelProvider?


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?


Solution

  • 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.

    override fun onDraw(canvas: Canvas) {
        if (isInEditMode) return
        ...
    }
    

    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.