【发布时间】:2023-03-12 11:45:01
【问题描述】:
我想计算表中所有记录的权重字段总和,我试过了:
在道课中
@Dao
interface FooDAO {
@Query("SELECT sum(purchaseWeight) FROM myTable")
suspend fun calculateSumOfAllWeight(): Int
}
在存储库类中
class FooRepository(application: Application) {
private var fooDAO: FooDAO
private var sumOfAllWeight = MutableLiveData<Int>()
init {
// skipping other code
CoroutineScope(Dispatchers.IO).launch {
sumOfAllWeight.postValue(fooDAO.calculateSumOfAllWeight())
}
}
fun getSumOfAllWeight(): MutableLiveData<Int> {
Log.e("SUM_OF_WEIGHT", " sumOfAllWeight "+ sumOfAllWeight.value)
return sumOfAllWeight
}
}
但它会打印出来
E/SUM_OF_WEIGHT: sumOfAllWeight null
在 logcat 中,我提到了 This Link 在 sqlite 中使用 sum()。
更新
@Query("SELECT sum(purchaseWeight) as value FROM myTable")
suspend fun calculateSumOfAllWeight(): Int
发现This并更新
@Query("SELECT COALESCE(sum(COALESCE(purchaseWeight,0)), 0) From myTable")
suspend fun calculateSumOfAllWeight(): Int
但仍然返回相同的null
【问题讨论】:
标签: android android-room android-architecture-components android-mvvm