Unexpected NullPointerException in Custom View's onDraw Method in Android 14
Quick question that's been bugging me - I'm a bit lost with I'm working with a `NullPointerException` in the `onDraw` method of my custom view, but I need to seem to figure out why it's happening. The view works perfectly most of the time, but occasionally, when I rotate the device or change the app's configuration, the `onDraw` method throws this behavior: `java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.Paint android.graphics.Canvas.getPaint()' on a null object reference`. Here's the relevant part of my custom view's implementation: ```kotlin class MyCustomView(context: Context, attrs: AttributeSet) : View(context, attrs) { private lateinit var paint: Paint init { paint = Paint().apply { color = Color.RED style = Paint.Style.FILL } } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) // This line occasionally causes a NullPointerException canvas.drawPaint(paint) } } ``` To handle configuration changes, I have tried overriding the `onSaveInstanceState` and `onRestoreInstanceState` methods, but it doesn't seem to solve the question. I also considered that it might be related to the view not being properly initialized after a configuration change, but I have ensured that `paint` is only initialized in the `init` block, which should execute only once. I've also ensured that Iām not accidentally creating a new instance of the view when recreating the activity. However, the scenario continues intermittently, and I want to reproduce it consistently. I've tested this on Android 14 (API level 34) devices, and it seems to be specific to the emulator. Any ideas on what could be causing this `NullPointerException` in the `onDraw` method, or how I can ensure that the view's state is preserved correctly during configuration changes? For context: I'm using Kotlin on Ubuntu 20.04. Thanks for your help in advance! What am I doing wrong?