我想将每个RealmResults数据发布到REST端点,并希望在发送成功时删除其数据。
运行以下代码,成功发送但无法删除
我尝试在target.deleteFromRealm()
中使用Response()
,但发生了IllegalStateException。
java.lang.IllegalStateException: Realm access from incorrect thread.
Realm objects can only be accessed on the thread they were created.
如何删除target
?
(使用Realm Java 3.1.2和Retrofit 2.2.0)
RealmResults<Model> results = realm.where(Model.class).findAll();
for ( final Model target: results ){
Call<Void> task = restInterface.post(gson.toJson(target));
task.enqueue( new CallBack<Void>(){
@Override
public void onResponse(Call<Void> call, Response<Void> response) {
// ?? how to delete target from realm ??
}
@Override
public void onFailure(Call<Void> call, Throwable t) {
// do nothing
}
});
}
答案 0 :(得分:0)
与删除普通ArrayLists的项目相同。这也是不允许的,并且会抛出ConcurrentModificationException。
另外我建议不要逐个发送项目到服务器,而是将它们收集到数组中并在一个请求中传递所有数据。
要将所有数据收集到ArrayList中,您可以使用
RealmResults<Model> results = realm.where(Model.class).findAll();
ArrayList<Model> list = new ArrayList(results);
然后尝试发送这样的数据:
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
}
});