Lateinit property has not been initialized (Android, Kotlin)

Viewed 5253

I'm currently working with a room database in my journal app. However, whenever I try to insert a new entry into my app without changing the bitmap variable by picking an image, my app crashes and displays this error.

2020-12-24 22:44:35.296 31023-31023/com.google.gradient.red E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.google.gradient.red, PID: 31023
    kotlin.UninitializedPropertyAccessException: lateinit property bitmap has not been initialized
        at com.google.gradient.red.fragments.add.addFragment.insertDataToDb(AddFragment.kt:132)
        at com.google.gradient.red.fragments.add.addFragment.onOptionsItemSelected(AddFragment.kt:111)

Here is my code:

// I make my bitmap variable
lateinit var bitmap: Bitmap

override fun onAttach(context: Context) {
        super.onAttach(context)
        var bitmap: Bitmap? = null
    }

Line 111 is when I call my insertDataToDb() function, and line 132 is in newData where I'm trying to insert my bitmap variable.

1 Answers

kotlin.UninitializedPropertyAccessException: lateinit property bitmap has not been initialized

The error message is clear. You've defined a lateinit field but never initialized it.
In your code here:

// I make my bitmap variable
lateinit var bitmap: Bitmap

override fun onAttach(context: Context) {
    super.onAttach(context)
    var bitmap: Bitmap? = null
}

You're defining a lateinit var called bitmap. So, since you used the keyword lateinit, you definitely should initialize it somewhere. Which, I guess, is what you were trying to do in the onAttach method. However, you're defining a new "locale" variable instead of initializing the original one. So, remove the onAttach method and change this:

lateinit var bitmap: Bitmap

To this:

var bitmap: Bitmap? = null
Related