[sum()的Sqlite函数对于房间持久性库似乎无法正常工作

问题描述 投票:0回答:1

我想计算表中所有记录的权重字段之和,我尝试过:

道课中

@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()。

更新

我已经搜索并找到thisthis SO个帖子并进行了更新

@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
1个回答
0
投票
当表为空时,sql中的聚合函数返回null。只有COUNT函数返回0。您还读取了LivaData的值,该值是异步更新的,并且不确定查询是否已执行。尝试在挂起函数之后的init块中放置一个日志,以测试返回值。
© www.soinside.com 2019 - 2024. All rights reserved.