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 the data into realm.
Realm realm = null;
try {
realm = Realm.getDefaultInstance();
realm.executeTransactionAsync(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
for (AppItem item : items) {
AppItem item2 = realm.createObject(AppItem.class, UUID.randomUUID().toString());
item2.mName = item.mName;
item2.mCount = item.mCount;
item2.mUsageTime = item.mUsageTime;
}
}
});
} finally {
if (realm != null) {
realm.close();
}
}
Then I am trying to access it in onPostExecute in AsyncTask, In doInBackground, I am getting the RealmResults<AppItem>, then storing it into List <AppItem> and sending it to onPostExecute where this code is placed. appItems is ReamObject here
Realm backgroundRealm = Realm.getDefaultInstance();
backgroundRealm.executeTransactionAsync(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
for (AppItem item : appItems) {
//getting error here if (item.mUsageTime <= 0) continue;
mTotal += item.mUsageTime;
item.mCanOpen = mPackageManager.getLaunchIntentForPackage(item.mPackageName) != null;
}
}
});
Both I have done using executeTransactionAsync, still I get the following error.
java.lang.IllegalStateException: Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created.