Android中的foreach RealmResults和delete
我想将每个RealmResults数据发布到REST端点,如果发送成功,我想删除它的数据 正在运行以下代码,发送成功但删除失败。Android中的foreach RealmResults和delete,android,retrofit2,realm-java,Android,Retrofit2,Realm Java,我想将每个RealmResults数据发布到REST端点,如果发送成功,我想删除它的数据 正在运行以下代码,发送成功但删除失败。 我试图在Response()中使用target.deleteFromRealm(),但发生了非法状态异常 java.lang.IllegalStateException: Realm access from incorrect thread. Realm objects can only be accessed on the thread they
我试图在
Response()
中使用target.deleteFromRealm()
,但发生了非法状态异常
java.lang.IllegalStateException: Realm access from incorrect thread.
Realm objects can only be accessed on the thread they were created.
如何删除目标?
(使用RealmJava3.1.2和改进版2.2.0)
RealmResults results=realm.where(Model.class).findAll();
用于(最终模型目标:结果){
调用task=restInterface.post(gson.toJson(target));
task.enqueue(新回调(){
@凌驾
公共void onResponse(调用、响应){
//?如何从域中删除目标??
}
@凌驾
失败时公共无效(调用调用,可丢弃的t){
//无所事事
}
});
}
这与删除普通ArrayList的项相同。这也是不允许的,将抛出ConcurrentModificationException
我还建议不要将项目逐个发送到服务器,而是将它们收集到数组中,并在一个请求中传递所有数据
要将所有数据收集到ArrayList中,可以使用
RealmResults<Model> results = realm.where(Model.class).findAll();
ArrayList<Model> list = new ArrayList(results);
RealmResults results=realm.where(Model.class).findAll();
ArrayList=新的ArrayList(结果);
然后尝试发送如下数据:
Call<Void> task = restInterface.post(gson.toJson(list));
task.enqueue( new CallBack<Void>(){
@Override
public void onResponse(Call<Void> call, Response<Void> response) {
// As a result all data will be uploaded in the same one batch and you can safely clear the db
results.deleteAllFromRealm();
}
@Override
public void onFailure(Call<Void> call, Throwable t) {
// do nothing
}
});
调用task=restInterface.post(gson.toJson(list));
task.enqueue(新回调(){
@凌驾
公共void onResponse(调用、响应){
//因此,所有数据将在同一批中上载,您可以安全地清除数据库
results.deleteAllFromRealm();
}
@凌驾
失败时公共无效(调用调用,可丢弃的t){
//无所事事
}
});
“ConcurrentModificationException”仅在循环仍处于活动状态时调用回调
gson.toJson(list)
OP的帖子中没有任何内容表明端点也接受列表,而不是单个items@njzk2这是真的,这只是我的建议(使用一个请求而不是多个请求)“我试图使用deleteFromRealm(),但失败。”定义“失败”。由于未复制领域对象,因此您正在访问相同的对象;您是否尝试过更新已成功发送的对象,如名为status set to synced的列;然后在完成后将其删除?
Call<Void> task = restInterface.post(gson.toJson(list));
task.enqueue( new CallBack<Void>(){
@Override
public void onResponse(Call<Void> call, Response<Void> response) {
// As a result all data will be uploaded in the same one batch and you can safely clear the db
results.deleteAllFromRealm();
}
@Override
public void onFailure(Call<Void> call, Throwable t) {
// do nothing
}
});