Reputation: 1701
I have a singleton class 'RealmDatabaseManager' where i have synchronized
methods for reading/writing from realm local database.
The methods look like this:
public long getPendingImagesCount() {
synchronized (this) {
realm = Realm.getInstance(RealmUtils.getRealmConfiguration());
long count = realm.where(PatientRecordImage.class)
.count();
realm.close();
return count;
}
}
Where this
is the instance of singleton class.
These methods are accessed from main as well as worker threads via the singleton instance. Every method creates and closes it's own realm.
The code works without issues on the devices i'm testing on but I've received Crashlytics reports from some devices giving two fatal errors.
IllegalStateException: Realm objects can only be accessed on the thread they were created.
And
IllegalStateException: Realm instance can only be closed on the thread it was created.
What is wrong with this approach? Can provide more info if needed.
Upvotes: 0
Views: 326
Reputation: 81539
Probably because you're setting the class variable to another Realm, and you have some fairly intricate multi-threading problem going on; nothing to do with device-specificness.
Solution: don't set the class level variable?
public long getPendingImagesCount() {
try(Realm realm = Realm.getInstance(RealmUtils.getRealmConfiguration())) {
return realm.where(PatientRecordImage.class).count();
}
}
Upvotes: 1