So inside a IntentService
, the app maybe active or inactive , onHandleIntent
gets called , where I have placed this below code.This is where I store th
As per the error message: Once you obtain any Realm objects on 1 thread, they can ONLY be accessed on that thread. Any access on other threads will throw that exception.
"doInBackground" from AsyncTask is run on a background thread. "onPostExecute" is run on the UI thread. So here you get Realm objects on a background thread, and try to access them on the UI thread => Exception.
You should either do everything on the background thread, or everything on the UI thread.
If you're doing a very complex query, i suggest using "findAllAsync" on the RealmQuery, as this will run the query on a background thread, and move them over to the main thread, but it's handled internally by Realm in a safe manner.
for (AppItem item : appItems) {
If appItems
contains managed RealmObjects that you obtained from a RealmResults on the UI thread, then accessing them will fail on the background thread.
realm.executeTransactionAsync((realm) -> {
gives you a Realm as parameter that is running on Realm's thread executor, so that must be used to obtain managed RealmResults/RealmObjects inside the transaction.
So you need to re-query the objects inside realm.executeTransactionAsync
if the objects are managed.
public void execute(Realm realm) {
for (AppItem item : realm.where(AppItem.class).findAll()) {