Issue
I am new to android and database, and studying Room Database from Google website. When I try to test the the methods in SleepDataBaseDao, sleepDao.get() always returns null. Here is the code. The insertAndGetNight() passes, but testGet() fails. I have no idea why this happens.
@Test
@Throws(Exception::class)
fun insertAndGetNight() {
val night = SleepNight()
sleepDao.insert(night)
val tonight = sleepDao.getTonight()
assertEquals(tonight?.sleepQuality, -1)
}
@Test
@Throws(Exception::class)
fun testGet() {
val night : SleepNight = SleepNight()
val nightID : Long = night.nightId
sleepDao.insert(night)
val finalNight = sleepDao.get(nightID)
assertEquals(finalNight?.nightId, nightID)
}
@Dao
interface SleepDatabaseDao {
@Insert
fun insert(night: SleepNight)
@Update
fun update(night: SleepNight)
@Query("SELECT * FROM daily_sleep_quality_table WHERE nightId=:key")
fun get(key: Long): SleepNight
@Query("DELETE FROM daily_sleep_quality_table")
fun clear()
@Query("SELECT * FROM daily_sleep_quality_table ORDER BY nightId DESC LIMIT 1")
fun getTonight(): SleepNight?
@Query("SELECT * FROM daily_sleep_quality_table ORDER BY nightId DESC")
fun getAllNights():LiveData<List<SleepNight>>
}
@Entity(tableName = "daily_sleep_quality_table")
data class SleepNight(
@PrimaryKey(autoGenerate = true)
var nightId: Long = 0L,
@ColumnInfo(name = "start_time_milli")
var startTimeMilli: Long = System.currentTimeMillis(),
@ColumnInfo(name = "end_time_milli")
var endTimeMilli: Long = startTimeMilli,
@ColumnInfo(name = "quality_rating")
var sleepQuality: Int = -1
)
Thanks for any help!
Solution
You have default id 0 in your SleepNight class but autoGenerate is true. I think that when you are creating new SleepNight your nightID is 0, but ids in database table starting from 1 and dao cant find it.
Answered By - Mirek Hýbler
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.