Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Room Database error: Unused parameter: days in @Query function

I'm using Room databse, trying to write a query in my Dao, which will delete all records older than specific amount of days. Here is what i come to:

 @Query("DELETE FROM my_table WHERE dateFrom <= date('now','-:days day')")
fun deleteAllOlderThan(days: Int)

However, when i try to build my project i get an error in my Gradle Console:

error: Unused parameter: days

I am using Kotlin, so it also show me this:

Error:Execution failed for task ':nexo:kaptDebugKotlin'. Internal compiler error. See log for more details

What is wrong with my Query?

UPDATE

I am also getting an error about converting Date. Here is my converter:

class Converter {
@TypeConverter
fun fromTimestamp(value: Long?) = value?.let { Date(it) }

@TypeConverter
fun dateToTimestamp(date: Date?) = date?.time
}

I am also adding it to my Database with annotation:

@TypeConverters(Converter::class)

Here is specific error i get:

Cannot figure out how to save this field into database. You can consider adding a type converter for it. e: e:private final java.util.Date dateFrom = null;

SUMMARY

  1. I was trying to use Converter with sealed class which in Room it causes problems, so i decided to keep my date parameter as Long.

  2. Check Emmanuel S answer. It should be:

    @Query("DELETE FROM my_table WHERE dateFrom <= date('now', '-' || :days || ' days')")
    fun deleteAllOlderThan(days: Int)
    
like image 560
K.Os Avatar asked Dec 07 '22 16:12

K.Os


2 Answers

I think CW gave the answer already for your: days issue.

Your days must be quoted as a string like

"-20 days"


@Query("DELETE FROM my_table WHERE dateFrom <= date('now', :days)")
fun deleteAllOlderThan(days: String)

If it's not working, concat may help.

Try:

@Query("DELETE FROM my_table WHERE dateFrom <= date('now', '-' || :days || ' days')")
fun deleteAllOlderThan(days: Int)

For your Converter issue, you may want to use

@TypeConverter
fun fromTimestamp(value: Long?) = value?.let { Date(it) }

@TypeConverter
fun dateToTimestamp(date: Date?) = date?.time 

which works just fine.

Don't use a companion object. Just use

class DBConverters { 
    @TypeConverter
    fun fromTimestamp(value: Long?) = value?.let { Date(it) }

    @TypeConverter
    fun dateToTimestamp(date: Date?) = date?.time
}

and add the Converter to your abstract DB class like

@TypeConverters(DBConverters::class)
abstract class YourDb : RoomDatabase() {}
like image 176
Emanuel S Avatar answered May 23 '23 12:05

Emanuel S


Inside the @Query string you need to put a : before days

like image 39
Nick Mowen Avatar answered May 23 '23 12:05

Nick Mowen