简体   繁体   中英

Android Room SUM Query returning null

I am trying to get the SUM of all transaction amounts from my TransactionDatabase but it's always returning null. Thanks for any help!!

This is my fragment

val transactionViewModelSum = ViewModelProvider(
            requireActivity(),
            TransactionViewModelFactory(requireActivity().application))
            .get(TransactionViewModel::class.java)

        transactionViewModelSum.getTransactionByDate().observe(viewLifecycleOwner, Observer {
            totalAmount = it.div(10)
        })

        if(totalAmount == null ) binding.cpbMainExpenses.progress = 15f else binding.cpbMainExpenses.progress = totalAmount!!.toFloat()

My DAO

 @Query("SELECT total(amount) FROM `Transaction`")
    fun getTransactionByDate(): LiveData<Double>

My Repository

fun getTransactionByDate(): LiveData<Double> {
        return transactionDao.getTransactionByDate()
    }

My View Model


private val liveTransactionDate = repository.getTransactionByDate()
...
fun getTransactionByDate(): LiveData<Double> = liveTransactionDate

Your Query looks like fine. I think problem in async working of this transactionViewModelSum.getTransactionByDate().observe() code. Try to put if(totalAmount == null ) binding.cpbMainExpenses.progress = 15f else binding.cpbMainExpenses.progress = totalAmount.!.toFloat() in observer lambda like bellow:

transactionViewModelSum.getTransactionByDate().observe(viewLifecycleOwner, Observer {
            totalAmount = it.div(10)
            if(totalAmount == null ) binding.cpbMainExpenses.progress = 15f else binding.cpbMainExpenses.progress = totalAmount!!.toFloat()
        })

I think that you try to read value of totalAmount before getTransactionByDate emits a value. If if I'am not right please write me about it in comment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM