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

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


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


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

Realm.getInstance(RealmConfiguration config) 

I used the Realm in IntentService

@Overrideprotected 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.