Realm.copyFromRealm 导致从不正确的线程访问 Realm。可能吗?
Realm.copyFromRealm cause Realm access from incorrect thread. is it possible?
来自错误线程的领域访问。领域对象只能在创建它们的线程上访问。
我用realm DB做报警服务
因此,为了获取 "time" 数据,我必须访问在其他线程中创建的对象。
所以我像下面的源一样复制了realmlist,但是在这部分出现了illegalstateexception。
还有其他解决方案吗?
Realm realm = Realm.getDefaultInstance();
List<DayWorkType> dayWorkTypesCopied = realm.copyFromRealm(dayWorkTypes);
//FAILED HERE
realm.close();
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
Realm realm = Realm.getDefaultInstance();
try {
List<DayWorkType> dayWorkTypesCopied = realm.copyFromRealm(dayWorkTypes);
} finally {
realm.close();
}
}
});
thread.start();
在使用 dayWorkTypes
之前,您需要提取它们的 ID 并在来自另一个 Realm 实例的请求中使用它们
//in your first/main thread
Set<String> dayWorkTypeIds = dayWorkTypes.map(d -> d.getId());
...
//in your new thread just query realm
Realm realm = Realm.getDefaultInstance();
RealmResults<DayWorkType> dayWorkTypes2 = realm
.where(DayWorkType.class)
.in("id", dayWorkTypeIds.toArray(new String[0]);
//now you can use dayWorkTypes2 as you want in your thread
来自错误线程的领域访问。领域对象只能在创建它们的线程上访问。
我用realm DB做报警服务
因此,为了获取 "time" 数据,我必须访问在其他线程中创建的对象。
所以我像下面的源一样复制了realmlist,但是在这部分出现了illegalstateexception。
还有其他解决方案吗?
Realm realm = Realm.getDefaultInstance();
List<DayWorkType> dayWorkTypesCopied = realm.copyFromRealm(dayWorkTypes);
//FAILED HERE
realm.close();
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
Realm realm = Realm.getDefaultInstance();
try {
List<DayWorkType> dayWorkTypesCopied = realm.copyFromRealm(dayWorkTypes);
} finally {
realm.close();
}
}
});
thread.start();
在使用 dayWorkTypes
之前,您需要提取它们的 ID 并在来自另一个 Realm 实例的请求中使用它们
//in your first/main thread
Set<String> dayWorkTypeIds = dayWorkTypes.map(d -> d.getId());
...
//in your new thread just query realm
Realm realm = Realm.getDefaultInstance();
RealmResults<DayWorkType> dayWorkTypes2 = realm
.where(DayWorkType.class)
.in("id", dayWorkTypeIds.toArray(new String[0]);
//now you can use dayWorkTypes2 as you want in your thread