Android领域错误的线程

时间:2015-12-09 17:44:15

标签: java android realm

我有2个服务,其中一个是生产者(将对象保存到领域),以及其他从领域读取此对象并在计划任务中将它们发送到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);
    }
}

DataStore实施:

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 个答案:

答案 0 :(得分:14)

你应该为每个线程使用自己的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 docs:

  

跨线程使用Realm的唯一规则是记住 Realm,   RealmObject或RealmResults 实例不能跨线程传递。

Using a Realm across Threads