@Insert fun insertMyStuff(" /> @Insert fun insertMyStuff(" /> @Insert fun insertMyStuff("/>

java.lang.reflect.InvocationTargetException while implementing Room Android

5.2k views Asked by At
@Dao
interface MyStuffDao {
    @Query("SELECT * FROM mystuff WHERE mid = :mid")
    fun selectByMid(mid: Long): ArrayList<MyStuff>

    @Insert
    fun insertMyStuff(mid: Long, name: String)

    @Delete
    fun deleteMyStuffName(mid: Long, name: String)

    @Delete
    fun deleteMyStuff(mid: Long)
}
@Entity(tableName = "mystuff")
data class MyStuff (
    @PrimaryKey(autoGenerate = true) val seq: Long,

    // this name is used in dao as column name
    @ColumnInfo(name = "mid") val mid: String,
    @ColumnInfo(name = "name") var name: String,
    @ColumnInfo(name = "created_at") var createdAt: String
)
@Database(entities = [MyStuff::class], version = 1, exportSchema = false)
abstract class MyDatabase : RoomDatabase() {
    abstract fun myStuffDao(): MyStuffDao

    companion object {
        const val DB_NAME = "MyDatabase.db"
        private var INSTANCE: MyDatabase? = null
        fun getMyDatabase(context: Context?): MyDatabase? {
            if (INSTANCE == null) {
                INSTANCE = Room.databaseBuilder(
                    context!!,
                    MyDatabase::class.java,
                    DB_NAME
                ).build()
            }
            return INSTANCE
        }

        fun destroyInstance() {
            INSTANCE = null
        }
    }
}

I get this error:

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:kaptDebugKotlin'.
> A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptExecution
   > java.lang.reflect.InvocationTargetException (no error message)

I've changed gradle, but they all didn't work.

2

There are 2 answers

2
Công Hải On

You can not declare @Insert or @Delete with custom parameter it should take entity instead like that.

@Insert
fun insertMyStuff(entity: MyStuff)

@Delete
fun deleteMyStuffName(entity: MyStuff)

@Delete
fun deleteMyStuff(entity: MyStuff)

More detail you can check here

All of the parameters of the Insert method must either be classes annotated with Entity or collections/array of it.

1
Ian On

I had the same exception. In my case it was because I'd forgotten to add @Entity to one of my model classes, e.g.

@Entity
data class Category(
    ...
    ...