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

前端 未结 3 1662
北海茫月
北海茫月 2020-12-31 03:17

I have some code that downloads a \"Current\" object\'s JSON. But this same code needs to be called by an IntentService whenever an alarm goes off (when the app is not runni

3条回答
  •  暖寄归人
    2020-12-31 03:50

    [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:

    • Using a Realm across Threads https://realm.io/docs/java/latest/#threading
    • Thread Example https://github.com/realm/realm-java/tree/master/examples/threadExample

提交回复
热议问题