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

前端 未结 3 1552
北海茫月
北海茫月 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
    0 讨论(0)
  • 2020-12-31 03:52

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

    0 讨论(0)
  • 2020-12-31 03:59

    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
    }
    
    0 讨论(0)
提交回复
热议问题