Android realm incorrect thread

泪湿孤枕 提交于 2020-01-03 16:54:58

问题


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);
}

回答1:


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



来源:https://stackoverflow.com/questions/34185491/android-realm-incorrect-thread

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!