[英]Android Room return LiveData in Dao in a subscription
[英]Android Room dao return null crash
我試圖通過在獲取遠程數據之前將本地數據返回到 UI 來實現離線第一個應用程序。
這是我的代碼
存儲庫
val trip: LiveData<DomainTrip> = Transformations.map(database.tripDao.getTrip(tripId)) {
it.asDomainModel()
}
suspend fun refreshTrip(token: String) {
withContext(Dispatchers.IO) {
val trip = webservice.getTrip(tripId, "Bearer $token").await()
database.tripDao.insertAll(trip.asDatabaseModel())
}
}
道
interface TripDao {
@Query("select * from databasetrip WHERE _id = :id")
fun getTrip(id: String): LiveData<DatabaseTrip>
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertAll(trip: DatabaseTrip)
}
視圖模型
private val tripRepository = TripRepository(getDatabase(application), tripId)
var trip = tripRepository.trip
如果用戶正在打開已存儲在數據庫中的行程,則上述代碼可以正常工作。 一旦用戶打開該行程, it.asDomainModel()
就會被調用。 一旦從遠程檢索到該行程並將其保存到數據庫中,就會再次調用it.asDomainModel()
。
我的問題是,如果用戶打開一個不在數據庫中的行程,上面的代碼在第一次調用it.asDomainModel()
時會崩潰, it
出現 null 指針異常。
更讓我困惑的是,如果上面的代碼應用於這個 dao 查詢
@Query("select * from databasetripinfo")
fun getTrips(): LiveData<List<DatabaseTripInfo>>
即使我的數據庫為空,我也不會在調用it.asDomainModel()
時得到任何 null 指針異常。
有人能幫幫我嗎? 當數據庫沒有該記錄時,如何避免 it.asDomainModel it.asDomainModel()
上的 null 指針異常?
謝謝
一切都好。 如果沒有給定 id 的項目,實時數據將返回 null。 您可以在映射之前檢查無效性( it?.asDomainModel
)
但是對於列表,您將得到空列表而不是 null (這是一個約定)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.