Soroush
Soroush

Reputation: 89

lateinit property context has not been initialized

I have a class which gets a context and uri and sets them in a MediaMetadatRetriever as dataSource. The problem is that I initialize context property with withContext function, but it seems to not being initialized and it ends up with a kotlin.UninitializedPropertyAccessException. Any help is appreciated.

Class:

class MyClass: Thread() {

    private lateinit var context: Context
    private lateinit var uri: Uri
    private val retriever = MediaMetadataRetriever()

    override fun run() {
        setRetriever()
    }

    fun withContext(context: Context) {
        this.context = context
    }

    fun withUri(uri: Uri) {
        this.uri = uri
    }

    fun setRetriever() {
        retriever.setDataSource(context, uri)
    }

    fun startThread() {
        MyClass().start()
    }
}

Main Activity:

val myClass = MyClass()
myClass.withContext(this)
myClass.withUri(uri)
myClass.startThread()

Exception:

kotlin.UninitializedPropertyAccessException: lateinit property context has not been initialized

Upvotes: 1

Views: 10418

Answers (1)

Demigod
Demigod

Reputation: 5635

The problem is that when call method startThread() you're creating new object every time with uninitialized property.

fun startThread() {
    MyClass().start()
}

You should replace MyClass().start() with this.start()

Upvotes: 2

Related Questions