我从sql db移到了房间。我不知道如何检查项目是否存在于数据库中。 如何使用Room编写此代码?
fun existsCheck(place: Places): Boolean {
val db= this.readableDatabase
val query = "SELECT * FROM $TABLE_PLACES WHERE $COLUMN_LAT = ${place.lat} AND $COLUMN_LNG = ${place.lng}"
val cursor = db.rawQuery(query, null)
if(cursor.count > 0){
cursor.close()
db.close()
return true
}
cursor.close()
db.close()
return false
}
我尝试使用此代码实现这一目标,但始终会返回FALSE
@Query("SELECT name FROM place WHERE lat = :lat AND lng = :lng")
fun exist(lat: Double?, lng: Double?): Flowable<String>
override fun save() {
Observable.just(dao)
.subscribeOn(Schedulers.io())
.subscribe { dao.insert(place) }
}
override fun itemExists(lat: Double?, lng: Double?): Single<Boolean> =
dao.exist(lat, lng)
.flatMapSingle { Single.just(it.isNotEmpty()) }
.onErrorReturn { false }
.first(false)
override fun delete() {
dao.deleteByLat(place.lat)
}
override fun saveClicked() {
var boolean = false
itemExists(place.lat, place.lng)
.subscribeOn(Schedulers.io())
.map { it -> boolean = it }
if (boolean){
delete()
v.setImageNotSaved()
} else {
save()
v.setImageSaved()
}
}
答案 0 :(得分:0)
这很好
override fun itemExists() {
Observable.just(dao)
.subscribeOn(Schedulers.io())
.subscribeOn(AndroidSchedulers.mainThread())
.map { it -> it.exist(place.lat, place.lng) }
.subscribe( { it -> saveClicked(true) },
{error -> saveClicked(false)})
}