Realm `access from incorrect thread` error when using shared code between IntentService and AsyncTask (Android)

人盡茶涼 提交于 2019-11-30 08:38:01
Roberto Artiles Astelarra

[UPDATED] based on the additional info

RealmDatabase.getInstance() was returning the Realm instance created on the main thread. And this instance was used on the IntentService's thread. Which lead to the crash.

Realm instances can't be used on any other thread except the one on which they were created.


You can't pass Realm objects between the threads. What you can do is to pass a unique identifier of the object (i.e. @PrimaryKey), and then fetch the object by its' id on another thread. Like this: realm.where(YourRealmModel.class).equalTo("primaryKeyVariable", id).findFirst().

For more details check out Realm's official documentation and example:

ayac3j

If you use the Realm in IntentService ,you will use new Realm .for example

Realm.getInstance(RealmConfiguration config) 

I used the Realm in IntentService

@Override
protected void onHandleIntent(Intent intent) {
    Realm realm = Realm.getDefaultInstance();
    ...
    realm.close(); // important on background thread
}

The problem is you are calling methods from differents threads, you have to use the same thread, create your own HandlerThread.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!