简体   繁体   中英

Query rows in the last seven days in android with room

I'm trying to get items from my sqlite datebase using android room. I have an app that keeps track of a dog's potty events.

my DAO looks like

 @Query("SELECT * FROM potty_events_table ORDER BY datetime DESC")
fun getPottyEvents(): LiveData<List<PottyEventModel>>

@Query("SELECT * FROM potty_events_table WHERE datetime >= DATE('now', '-7 day')")
fun getPottyEventsFromLastWeek(): LiveData<List<PottyEventModel>>

the get potty events works fine but not the one from last week. I also use the following converters. WHen I try to call my getPottyEventsFromLastWeek I get an empty array.

 @TypeConverter
fun fromTimestamp(value: Long): Calendar? {
    return value.let {
        val c = Calendar.getInstance()
        c.timeInMillis = it
        c
    }
}

@TypeConverter
fun calendarToTimestamp(calendar: Calendar?): Long? {
    return calendar?.timeInMillis
}

If your app API level is over 26 you can use the DateTimeFormatter and save the time in the database as a string.

So your converter looks like

private DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;

@TypeConverter
public OffsetDateTime toOffsetDateTime(String string) {
    return formatter.parse(string, OffsetDateTime::from);
}

@TypeConverter
public String fromOffsetDatetime(OffsetDateTime offsetDateTime) {
    return offsetDateTime.format(formatter);
}

I used that because it transfers well when across multiple timezones

which then your DOA would change slightly to be

 @Query("SELECT * FROM potty_events_table ORDER BY datetime(<example>)")
 fun getPottyEvents(): LiveData<List<PottyEventModel>>

Just replace <example> with the column name that has the string list

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