CRUD operations such as delete, add, select work quite correctly, but updates do not update anything in the database at all. I’m new to all this.
I am attaching the available code:
@Entity
@Entity(
tableName = "book",
foreignKeys = [
ForeignKey(
entity = User::class,
parentColumns = ["user_id"],
childColumns = ["user_id"],
onDelete = ForeignKey.NO_ACTION,
onUpdate = ForeignKey.NO_ACTION
)
]
)
data class Books(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "book_id")
val bookId: Int = 0,
@ColumnInfo(name = "user_id")
val userId: Int? = null,
@ColumnInfo(name = "image_url")
val imageUrl: String? = null,
@ColumnInfo(name = "title")
val title: String,
@ColumnInfo(name = "author")
val author: String? = null,
@ColumnInfo(name = "genre")
val genre: String? = null,
@ColumnInfo(name = "description")
val description: String? = null,
@ColumnInfo(name = "status")
val status: String? = null,
@ColumnInfo(name = "rating")
val rating: Double? = null,
@ColumnInfo(name = "creation_date")
val creationDate: Long = System.currentTimeMillis()
)
@Dao
@Update
suspend fun updateBook(book: Books)
@Database
@Database(entities = [User::class, Books::class, Chapters::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
abstract fun booksDao(): BooksDao
abstract fun chaptersDao(): ChaptersDao
companion object {
@Volatile
private var INSTANCE: AppDatabase? = null
private val LOCK = Any()
fun getDatabase(context: Context): AppDatabase {
return INSTANCE ?: synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
AppDatabase::class.java,
"app_database"
).build()
INSTANCE = instance
instance
}
}
operator fun invoke(context: Context) = INSTANCE ?:
synchronized(LOCK) {
INSTANCE ?:
createDatabase(context).also {
INSTANCE = it
}
}
private fun createDatabase(context: Context) =
Room.databaseBuilder(
context.applicationContext,
AppDatabase::class.java,
"app_database"
).build()
}
}
Repo
suspend fun updateBooks(books: Books) = db.booksDao().updateBook(books)
ViewModel
fun updateBooks(books: Books) =
viewModelScope.launch {
booksRepository.updateBooks(books)
}
Navigator
composable("change_book/{bookId}",
arguments = listOf(navArgument("bookId") {type = NavType.IntType})
) {backStackEntry ->
backStackEntry.arguments?.getInt("bookId")
?.let { ChangeBook(navController, database, userViewModel, it, updateBooks = { booksViewModel.updateBooks(it) }) }
}
Composable fun ChangeBook
val books = currentBooks?.let {
Books(
it.bookId,
imageUrl = updatedImage,
title = updatedTitle,
author = updatedAuthor,
genre = updatedGenre,
description = updatedDescription
)
}
if (books != null) {
updateBooks(books)
}
Everything is recorded successfully in the updateImage data and so on (the data in them is correct)
I changed @update to @query.
New contributor
Aro is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.