安卓 Realm 错误线程

4

我有两个服务,其中一个是生产者(将对象保存到Realm中),另一个读取这些对象并在定时任务中将它们发送到REST服务。

我的异常情况:

java.lang.IllegalStateException: Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created. 

服务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!");
                }
            }
        }
    });

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

数据存储实现:

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个回答

15

每个线程都应该使用自己的 Realm 实例:

// 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);
...

根据 Realm 文档:

在使用跨线程的 Realm 时,唯一需要记住的规则是不能将Realm、RealmObject 或 RealmResults实例传递到其他线程。

在多线程中使用 Realm


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接