我想在Android Room中向我的数据库插入一些数据。问题是,每次我请求我的数据时,结果都是null。
这是我的数据库代码:
@Database(entities = [VenueResult::class, VenueDetailResult::class], version = 1, exportSchema = false)
abstract class VenueFinderDatabase: RoomDatabase() {
abstract fun venueResultsDao(): VenueResultsDao
abstract fun venueDetailDao(): VenueDetailDao
companion object {
private var instance: VenueFinderDatabase? = null
fun getInstance(context: Context) : VenueFinderDatabase {
instance?.let {
return it
} ?: run {
synchronized(VenueFinderDatabase::class) {
Room.databaseBuilder(context.applicationContext,
VenueFinderDatabase::class.java, "venuefinder.db")
.build().let {
return it
}
}
}
}
}
}
这是我的道:
@Dao
interface VenueResultsDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(venueResult: VenueResult): Long
@Query("SELECT * FROM venueResult WHERE requestId = :requestId")
fun getVenueResultsForRequestId(requestId: String): LiveData<List<VenueResult>>
@Query("SELECT * FROM VenueResult WHERE search_value = :value")
fun getVenueResultsForSearchValue(value: String): LiveData<List<VenueResult>>
}
这是我的实体:
@Entity
data class VenueResult(
@PrimaryKey val id: String,
@ColumnInfo(name = "requestId") val requestId: String,
@ColumnInfo(name = "name") val name: String,
@ColumnInfo(name = "location_cc") val locationCC: String?,
@ColumnInfo(name = "location_city") val locationCity: String?,
@ColumnInfo(name = "location_state") val locationState: String?,
@ColumnInfo(name = "search_value") val searchValue: String
)
这是我的仪器测试:
@RunWith(AndroidJUnit4::class)
class VenueFinderDatabaseInstrumentedTest {
private lateinit var database: VenueFinderDatabase
private lateinit var venueResultsDao: VenueResultsDao
@Before
fun setup() {
val context = ApplicationProvider.getApplicationContext<Context>()
database = Room.inMemoryDatabaseBuilder(
context, VenueFinderDatabase::class.java
).build()
venueResultsDao = database.venueResultsDao()
}
@After
fun tearDown() {
database.clearAllTables()
database.close()
}
@Test
fun validateIfDataIsInsertedInDatabase() {
// Arrange
val searchValue = "New York"
val venueResult = getDummyVenueResult(searchValue)
// Act
venueResultsDao.insert(venueResult)
val result = venueResultsDao.getVenueResultsForSearchValue(searchValue).value?.first()
// Assert
assertNotNull(result)
//assertEquals(venueResult, result)
}
private fun getDummyVenueResult(value: String) =
VenueResult(
id = "5642aef9498e51025cf4a7a5",
requestId = "59a45921351e3d43b07028b5",
name = "Mr. Purple",
locationCC = "US",
locationCity = "New York",
locationState = "NY",
searchValue = value
)
}
有人能指出我做错了吗?为什么我的结果为null,我该如何解决这个问题?
有人能指出我做错了吗?
你在叫getVenueResultsForSearchValue()
。这将返回LiveData<List<VenueResult>>
。 IOW,它不是在做你的查询。它正在设置一个LiveData
,它会在观察到它时进行查询。所以,当你到达LiveData
获得价值时,它将是null
。
我怎样才能解决这个问题?
或者:
getVenueResultsForSearchValue()
返回List<VenueResult>
,或LiveData
and use InstantTaskExecutorRule()
to have your results performed synchronously