Home > database >  How to get specific value from room database by id?
How to get specific value from room database by id?

Time:01-29

I have a simple room database with LiveData, i want to get (cartPriceI: Double) values by id to use it within specific methods.

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()
        }
    }
}

I'm a beginner, i want to know if there is possible way to do that and retrieve specific values from database (ex. cartPriceI in Double) by id!

CodePudding user response:

You can query the database by the given id and return it asynchronously either with a suspend fun or LiveData/Flow

In the CartItemsDAO:

@Query("SELECT cartPriceI FROM cart_table WHERE cid = :id")
suspend fun getPrice(id: Int): Double


@Query("SELECT cartPriceI FROM cart_table WHERE cid = :id")
fun getPrice(id: Int): LiveData<Double>

CodePudding user response:

You can get a specific model by SELECT with WHERE statement

@Query("SELECT * FROM cart_table WHERE cid == : cid")
fun getCartItemsDatabase(cid: String): LiveData<CartItemsDatabase?>

Or you can Return a subset of a table's columns

@Query("SELECT priceID FROM cart_table WHERE cid == : cid")
fun getCartItemPrice(cid: String): LiveData<Double>
  • Related