I have 2 Services, one of them is a producer (saving objects to realm), and other reading this objects from realm and sending them to REST service in scheduled tasks.
My exception:
java.lang.IllegalStateException: Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created.
Service 1:
this.scheduler.schedule("*/2 * * * *", new Runnable() {
public void run() {
List<Location> locations = dataStore.getAll(Location.class);
for(Location l : locations) {
try {
serverEndpoint.putLocation(l);
l.removeFromRealm();
} catch (SendingException e) {
Log.i(this.getClass().getName(), "Sending task is active!");
}
}
}
});
Service 2:
private LocationListener locationListener = new android.location.LocationListener() {
@Override
public void onLocationChanged(Location location) {
TLocation transferLocation = new TLocation();
transferLocation.setLat( location.getLatitude() );
transferLocation.setLng(location.getLongitude());
dataStore.save(transferLocation);
}
}
DataStore implementation:
public void save(RealmObject o) {
this.realm.beginTransaction();
this.realm.copyToRealm(o);
this.realm.commitTransaction();
}
public <T extends RealmObject> List<T> getAll(Class<T> type) {
return this.realm.allObjects(type);
}
You should use own instance of Realm for each thread:
// Query and use the result in another thread
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
// Get a Realm instance for this thread
Realm realm = Realm.getInstance(context);
...
From the Realm docs:
The only rule to using Realm across threads is to remember that Realm, RealmObject or RealmResults instances cannot be passed across threads.
Using a Realm across Threads
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With