Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android realm incorrect thread

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);
}
like image 245
kris14an Avatar asked Dec 05 '22 19:12

kris14an


1 Answers

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

like image 124
Ilya Tretyakov Avatar answered Dec 08 '22 07:12

Ilya Tretyakov