Android Room SUM Query returning null

Viewed 113

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
1 Answers

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.

Related