我想使用Room
数据库,但是在构建应用程序时出现此错误:
执行org.jetbrains.kotlin.gradle.internal.KaptExecution时发生故障
和类似这样的错误:
错误:不确定如何将Cursor转换为该方法的返回类型(java.util.ArrayList
)。
我将Room
数据库用于以下类:
书签实体:
@Entity(tableName = "bookmark")
class BookmarkEntity(
@PrimaryKey(autoGenerate = true)
var id: Int,
@ColumnInfo(name = "TITLE")
var title: String,
@ColumnInfo(name = "URL")
var url: String,
@ColumnInfo(name = "IMAGE")
var image: String
)
BookmarkDataBase:
@Database(entities = [BookmarkEntity::class], version = 1)
abstract class BookmarkDataBase : RoomDatabase() {
abstract fun bookmark(): BookmarkDAO
companion object {
private var instance: BookmarkDataBase? = null
fun getInstance(context: Context): BookmarkDataBase {
if (instance == null)
instance =
Room.databaseBuilder(context, BookmarkDataBase::class.java, "bookmark")
.allowMainThreadQueries()
.fallbackToDestructiveMigration()
.build()
return instance!!
}
}
}
书签DAO:
@Dao
interface BookmarkDAO {
@Insert
fun insertData(bookmarkEntity: BookmarkEntity): Boolean
@Query("select * from bookmark")
fun getData(): ArrayList<BookmarkModel>
@Query("DELETE FROM bookmark WHERE id = :id")
fun deleteData(id: Int)
@Delete
fun deleteData(bookmarkEntity: BookmarkEntity)
}
我为Room
添加了此依赖项:
implementation "androidx.room:room-runtime:2.2.5"
kapt "androidx.room:room-compiler:2.2.5"
并在 build.gradle 文件顶部添加apply plugin: 'kotlin-kapt'
。但是该错误仍然会发生。你能帮我吗?
答案 0 :(得分:2)
问题是Room
的查询函数只能返回由@Entity
注释的类的实例。因此,BookmarkDAO.getData()
无法返回BookmarkModel
的列表。
所以:
@Query("select * from bookmark")
fun getData(): List<BookmarkEntity>
答案 1 :(得分:1)
我猜你不能返回arraylist,只能删除并使用list。
@Query("select * from bookmark")
fun getData(): ArrayList<BookmarkModel>