我有一个带有LiveData的简单房间数据库,我想获取(cartPriceI:Double)值,以便在特定方法中使用它。
CartItemsDatabase.kt
@Parcelize
@Entity(tableName = "cart_table")
data class CartItemsDatabase(
@PrimaryKey(autoGenerate = true) var cid: Int,
@ColumnInfo(name = "titleD") var cartTitle: String?,
@ColumnInfo(name = "imageD") var cartImage: Bitmap?,
@ColumnInfo(name = "priceLD") var cartPriceL: Double?,
@ColumnInfo(name = "priceID") var cartPriceI: Double?,
@ColumnInfo(name = "itemNumD") var cartNum: Int?,
@ColumnInfo(name = "descriptionD") var cartDes: String?): Parcelable
CartItemsDAO.kt
@Dao
interface CartItemsDAO {
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun addItem(cartItemsDatabase: CartItemsDatabase)
@Update
suspend fun updateCart(cartItemsDatabase: CartItemsDatabase)
@Query("SELECT * FROM cart_table ORDER BY cid ASC")
fun readAllData(): LiveData<List<CartItemsDatabase>>
@Delete
fun delete(cartItems: CartItemsDatabase)
}
CartRepository.kt
class CartRepository(private val cartItemsDAO: CartItemsDAO) {
val readAllData: LiveData<List<CartItemsDatabase>> = cartItemsDAO.readAllData()
suspend fun addItem(cartItemsDatabase: CartItemsDatabase){
cartItemsDAO.addItem(cartItemsDatabase)
}
suspend fun updateCart(cartItemsDatabase: CartItemsDatabase){
cartItemsDAO.updateCart(cartItemsDatabase)
}
}
CartViewModel.kt
class CartViewModel(application: Application): AndroidViewModel(application) {
val readAllData: LiveData<List<CartItemsDatabase>>
private val repository: CartRepository
init {
val cartDao = AppDatabase.getDatabase(application).cartDao()
repository = CartRepository(cartDao)
readAllData = repository.readAllData
}
fun addItem(cartItemsDatabase: CartItemsDatabase){
viewModelScope.launch(Dispatchers.IO){
repository.addItem(cartItemsDatabase)
}
}
fun updateCart(cartItemsDatabase: CartItemsDatabase){
viewModelScope.launch(Dispatchers.IO) {
repository.updateCart(cartItemsDatabase)
}
}
}
AppDatabase.kt
@Database(entities = [CartItemsDatabase::class], version = 1, exportSchema = false)
@TypeConverters(Converters::class)
abstract class AppDatabase : RoomDatabase() {
abstract fun cartDao(): CartItemsDAO
companion object {
@Volatile
private var INSTANCE: AppDatabase? = null
fun getDatabase(context: Context): AppDatabase {
// if the INSTANCE is not null, then return it,
// if it is, then create the database
val tempInstance = INSTANCE
if (tempInstance != null){
return tempInstance
}
synchronized(this){
val instance = Room.databaseBuilder(
context.applicationContext,
AppDatabase::class.java,
"cart_database"
).build()
INSTANCE = instance
return instance
}
}
private fun buildDatabase(context: Context): AppDatabase {
return Room.databaseBuilder(
context.applicationContext,
AppDatabase::class.java,
"cartItems_database"
)
.build()
}
}
}
我是一个初学者,我想知道是否有可能的方法来做到这一点,并从数据库中检索特定的值(如cartPriceI在双)的id!
2条答案
按热度按时间hrysbysz1#
您可以通过给定的
id
查询数据库,并使用suspend函数或LiveData/Flow异步返回在
CartItemsDAO
:w51jfk4q2#
通过
WHERE
语句,可以通过SELECT
得到特定的模型也可以返回表列的子集