I would like to have method like this in my dao object
@Query("SELECT c.name, sum(p.value) FROM payments p, paymentCategories c WHERE p.categoryId = c.id GROUP BY c.name")
fun getCategoryStats(): Map<String, Float>
but i get the error
error: Not sure how to convert a Cursor to this method's return type public abstract java.util.Map
Is it possible to change it to working version?
So it can be different type to return but the main conditions are
I'm little late for a party but maybe someone will still search for it.
From Room 2.4 we are able to use multimap return type with annotation @MapInfo which allow us to define the mapping for key and value.
In your case it will be sth like this:
@MapInfo(keyColumn = "name", valueColumn = "sum")
@Query("SELECT c.name AS name, sum(p.value) AS sum FROM payments p, paymentCategories c WHERE p.categoryId = c.id GROUP BY c.name")
fun getCategoryStats(): Map<String, Float>
More info: https://developer.android.com/training/data-storage/room/accessing-data#multimap
Update
@MapInfo was deprecated. Here's the new way to do it in Kotlin:
@Query("SELECT c.name AS name, sum(p.value) AS sum FROM payments p, paymentCategories c WHERE p.categoryId = c.id GROUP BY c.name")
suspend fun getCategoryStats(): Map<@MapColumn(columnName = "name") String, @MapColumn(columnName = "sum") Float>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With