How to insert, update, delete, and get items from room database in jetpack compose? Want to insert, update, delete, and get items from room database. How to do that? I'am created entity class, dao, and database class.
@Entity(tableName = "items")
data class Item(
@PrimaryKey(autoGenerate = true)
val id: Int,
val name: String,
val price: Int,
val quantity: Int
)
@Dao
interface ItemDao {
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insert(item: Item)
@Update
suspend fun update(item: Item)
@Delete
suspend fun delete(item: Item)
@Query("SELECT * from items WHERE id = :id")
fun getItem(id: Int): Flow<Item>
@Query("SELECT * from items ORDER BY name ASC")
fun getAllItems(): Flow<List<Item>>
}
@Database(entities = [Item::class], version = 1, exportSchema = false)
abstract class InventoryDatabase : RoomDatabase() {
abstract fun itemDao(): ItemDao
companion object {
@Volatile
private var Instance: InventoryDatabase? = null
fun getDatabase(context: Context): InventoryDatabase {
return Instance ?: synchronized(this) {
Room.databaseBuilder(context, InventoryDatabase::class.java, "item_database")
.build()
.also { Instance = it }
}
}
}
}
Well, to do any of those (add / update / delete etc.) you need a database instance, so wherever you want to use the database you have to create the instance:
val db = Room.databaseBuilder(
applicationContext, // or requireContext(), depends where you are, but it just needs context
AppDatabase::class.java,
"database-name"
).build()
and then AFTER you create the instance, you can get the DAO that allows you to interact with the db:
val dao = db.itemDao()
and then you can simply use the dao's functions, like:
dao.insert(Item(...))
all of those steps are mentioned in the documentation: https://developer.android.com/training/data-storage/room and I would higly recommend you to follow / read it :D,
cheers!