简体   繁体   English

在所有线程上使用领域

[英]Use realm across all threads

I have DBManager class for CRUD operations and I want to use it across application, I know that Realm objects can only be accessed on the thread they were created and for that reason I'm unable to use My DBManager class methods inside threads and etc... 我有用于CRUD操作的DBManager类,我想在整个应用程序中使用它,我知道Realm对象只能在它们创建的线程上访问,因此,我无法在线程等中使用My DBManager类方法。 ..

what I want is to call updateUploadingFileStatus method declared inside DBManager, from thread which is running inside service. 我想要的是从服务内部运行的线程调用DBManager内部声明的updateUploadingFileStatus方法。

this is my DBManager class 这是我的DBManager类

object DbManager {
private val realm: Realm by lazy { Realm.getDefaultInstance() }

fun saveOrRemoveUploadFile(filePath: String, save: Boolean){
    val model = getUploadModelByFilePath(filePath)
    realm.executeTransaction {
        model.markedForUpload = save
        realm.insertOrUpdate(model)
    }
}

fun updateUploadingFileStatus(filePath: String, uploaded: Boolean){
    val model = getUploadModelByFilePath(filePath)
    realm.executeTransaction {
        model.uploadedStatus = uploaded
    }
}

fun getFilesForUpload() : List<UploadModel> {
    return realm
            .where(UploadModel::class.java)
            .equalTo("markedForUpload",true)
            .equalTo("uploadedStatus",false)
            .findAll()
}

fun getUploadModelByFilePath(filePath: String) : UploadModel {
    return realm.where(UploadModel::class.java).equalTo("filePath",filePath).findFirst() ?: UploadModel(filePath)
}

}

Calling this method from another thread throws java.lang.IllegalStateException Realm access from incorrect thread. 从另一个线程调用此方法会java.lang.IllegalStateException Realm access from incorrect thread.引发java.lang.IllegalStateException Realm access from incorrect thread. How can be solved this problem? 如何解决这个问题? what is a good style for doing things like that? 做这样的事情的好风格是什么?

Change your function code as follow: 如下更改功能代码:

 public void updateUploadingFileStatus(final String filePath, final Boolean uploaded) {
        mRealm.executeTransactionAsync(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                UploadModel model = getUploadModelByFilePath(filePath);
                model.uploadedStatus = uploaded;
            }
        });
    }

Time ago I solved this problem by using a new Transaction. 前一段时间,我通过使用新的事务解决了这个问题。 I also was using a Singleton class to access the RealmDB, and was calling this function inside a response handler from network. 我还使用Singleton类访问RealmDB,并在来自网络的响应处理程序中调用此函数。 This should work. 这应该工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM