Search code examples
androidkotlinnullpointerexceptionsurfaceviewlateinit

Kotlin SurfaceView / lateinit property surface has not been initialized


I’m still quite green and don’t know some of the features of the language. I face the following problem here is my code:

private lateinit var surface: SurfaceView
private var _binding: FragmentItem2Binding? = null
private val binding get() = _binding!!

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
    ): View? {
    _binding = FragmentItem2Binding.inflate(inflater, container, false)
    return binding.root

     }


override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    surface?.findViewById<SurfaceView>(R.id.surf)
        this.surface!!.holder!!.addCallback(object : SurfaceHolder.Callback {
            override fun surfaceCreated(holder: SurfaceHolder) {
               TODO("Not yet implemented")
            }

            override fun surfaceChanged(
               holder: SurfaceHolder,
               format: Int,
               width: Int,
               height: Int,
            ) {
               TODO("Not yet implemented")
            }

            override fun surfaceDestroyed(holder: SurfaceHolder) {
               TODO("Not yet implemented")
            }
        })

xml:

\<SurfaceView
    android:layout_width="400sp"
    android:layout_height="400sp"
    android:id="@+id/surf"
\\\>

If I put:

lateinit var

it gives:

kotlin.UninitializedPropertyAccessException: lateinit property surface has not been initialized

If I put:

private var surface: SurfaceView? = null

it gives the error: java.lang.NullPointerException

What should I do?


Solution

  • You're not initializing the value anywhere. Try:

    surface = findViewById<SurfaceView>(R.id.surf)
    

    or in viewBinding:

    surface - viewBinding.surf //or what ever the id of the surface is