Property delegate must have a 'getValue(donorApp, KProperty*>)' method

Viewed 27
package com.example.bloodbank

import android.app.Application

class donorApp:Application(){
    val db by lazy{
        DonorDatabase.getInstance(this)
    }
}

I am trying to make an instance of the database to access the Dao but the lazy{} is not working it shows a error "Property delegate must have a 'getValue(donorApp, KProperty*>)' method. None of the following functions are suitable"

here the donor Database

package com.example.bloodbank

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase

@Database(entities = [DonorEntity::class], version = 2)
abstract class DonorDatabase:RoomDatabase() {
    abstract fun donorDao():DonorDao

    companion object{
        @Volatile
        private var INSTANCE:DonorDatabase?=null
        fun getInstance(context: Context):DonorDatabase{
            synchronized(this){
                var instance=INSTANCE
                if (instance==null){
                    instance=Room.databaseBuilder(context.applicationContext,
                        DonorDatabase::class.java,"donor_database")
                        .fallbackToDestructiveMigration().build()
                }
                INSTANCE=instance
                return instance
            }
        }
    }

}

here the Dao

package com.example.bloodbank

import androidx.room.*
import kotlinx.coroutines.flow.Flow

@Dao
interface DonorDao {
    @Insert
    suspend fun insert(donorEntity:DonorEntity)
    @Update
    suspend fun update(donorEntity:DonorEntity)
    @Delete
    suspend fun delete(donorEntity:DonorEntity)
    @Query("SELECT*FROM `donor-table`")
    fun fetchAllDonor(): Flow<List<DonorEntity>>
    @Query("SELECT*FROM `donor-table` Where id=:id")
    fun fetchOneDonor(id:Int): Flow<DonorEntity>
} 
1 Answers

I think your code shouldn't even compiler because your return type is DonorDatabase but you are returning nullable variable. You havent added !! operator also.

Since db non nullable, you can make it like below and remove extra instance variable.

@Database(entities = [DonorEntity::class], version = 2)
abstract class DonorDatabase:RoomDatabase() {
    abstract fun donorDao():DonorDao

    companion object{
        @Volatile
        private var INSTANCE:DonorDatabase?=null
        fun getInstance(context: Context):DonorDatabase{
            synchronized(this){
                if (INSTANCE ==null){
                    INSTANCE = Room.databaseBuilder(context.applicationContext,
                        DonorDatabase::class.java,"donor_database")
                        .fallbackToDestructiveMigration().build()
                }
                return INSTANCE!!
            }
        }
    }

}
Related