【问题标题】:Android realm incorrect threadAndroid领域不正确的线程
【发布时间】:2015-12-10 02:04:32
【问题描述】:

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

数据存储实现:

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

【问题讨论】:

    标签: java android realm


    【解决方案1】:

    您应该为每个线程使用自己的 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 实例不能跨线程传递。

    Using a Realm across Threads

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-06
      • 2017-09-23
      • 1970-01-01
      • 2019-08-04
      相关资源
      最近更新 更多