领域未更新对象

时间:2020-02-20 13:25:43

标签: android kotlin realm

我正在尝试在领域中找到特定对象并更新其上的某些字段。计划是查询我的数据库并根据主键查找我的对象。 Realm检索到我的对象后,便立即更改它的字段,然后尝试将其重新插入数据库中。

在另一个屏幕上,我正在读取更新的对象,但它似乎具有与以前相同的值。因此更新从未发生。

有什么想法吗?

这是我的更新方法:

fun updateObjectVisibility(code: String) {
    val realm = realmManager.getRealmInstance()

    realm.executeTransaction {
        val updatedModel = realm.where(MyModel::class.java)
                .equalTo("code", code)
                .findFirst()

        updatedModel?.visible = false
        it.insertOrUpdate(updatedModel!!)
    }

    realmManager.closeRealmInstance()
}

这是我的对象

@RealmClass
open class MyModel() : RealmObject() {
    @PrimaryKey
    var code: String? = null
    var filed1: String? = null
    var field2: String? = null
    var price: String? = null
    var visible: Boolean = true

    constructor(
            code: String,
            filed1: String,
            field2: String,
            price: String,
            visible: Boolean = true
    ): this() {
        this.code = code
        this.field1 = field1
        this.field2 = field2
        this.price = price
        this.visible = visible
    }
}

这是Realm Manager

class RealmManager {
    private val realm = ThreadLocal<Realm>()

    @Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS")
    fun getRealmInstance(): Realm {
        Realm.getDefaultConfiguration()?.let {
            if (realm.get() == null) {
                realm.set(Realm.getDefaultInstance())
                return realm.get()
            }
            return realm.get()
        }
        throw IllegalStateException("Realm should have a valid configuration")
    }

    fun closeRealmInstance() {
        Realm.getDefaultConfiguration()?.let {
            realm.get()?.close()
            if (Realm.getLocalInstanceCount(it) <= 0) {
                realm.set(null)
            }
            return
        }
        throw IllegalStateException("Realm should have a valid configuration")
    }
}

0 个答案:

没有答案
相关问题