skip to Main Content

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


  1. Chosen as BEST ANSWER

    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.


  2. 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():

    public boolean isInEditMode ()

    Indicates whether this View is currently in edit mode. A View is usually in edit mode when displayed within a developer tool. For instance, if this View is being drawn by a visual user interface builder, this method should return true. Subclasses should check the return value of this method to provide different behaviors if their normal behavior might interfere with the host environment. For instance: the class spawns a thread in its constructor, the drawing code relies on device-specific features, etc. This method is usually checked in the drawing code of custom widgets.

    private val mainViewModel by lazy {
        if (!isInEditMode) {
            ViewModelProvider(findViewTreeViewModelStoreOwner()!!).get<MainViewModel>()
        } else {
            null
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search