简体   繁体   中英

Android Room dao return null crash

I'm trying to implement offline first app by returning local data to UI before fetching remote data.

Here's my code

Repository

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())
    }
}

DAO

interface TripDao {
    @Query("select * from databasetrip WHERE _id = :id")
    fun getTrip(id: String): LiveData<DatabaseTrip>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insertAll(trip: DatabaseTrip)
}

ViewModel

private val tripRepository = TripRepository(getDatabase(application), tripId)
var trip = tripRepository.trip

If the user is opening a trip that is already stored in the database, above code works without any problem. it.asDomainModel() gets called as soon as user opens that trip. it.asDomainModel() gets called again as soon as that trip is retrieved from remote and saved into the database.

My problem is, if user is opening a trip that is not in the database, above code crashes when it.asDomainModel() is called the first time, with null pointer exception on it .

What confuses me more is that if above code were applied to this dao query

@Query("select * from databasetripinfo")
fun getTrips(): LiveData<List<DatabaseTripInfo>>

i won't get any null pointers exception on both call of it.asDomainModel() even when my database is empty.

Can somebody please help me? How do I avoid null pointer exception on it.asDomainModel() when database does not have that record?

thx

It's all OK. If there is no item with the given id, the live data will return null. You can check for nullity before mapping in the transformation ( it?.asDomainModel )

However for lists you will get empty list instead of null (it's a convention).

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