我有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() { Listlocations = 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(); } publicList getAll(Class type) { return this.realm.allObjects(type); }
Ilya Tretyak.. 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实例:
// 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实例不能跨线程传递.
跨线程使用领域