领域:getTable()删除所有copyToRealm

时间:2016-01-30 11:38:01

标签: realm

我有这段代码,其目标是删除所有配方对象,删除这些对象后,我将使用列表中的新配方再次填充表格。

realm.beginTransaction();
realm.getTable(Recipe.class).clear();
realm.copyToRealm(list);
realm.commitTransaction();

此代码的问题是它抛出此异常

Value already exists: 18
io.realm.exceptions.RealmPrimaryKeyConstraintException: Value already exists: 18
    at io.realm.internal.Table.throwDuplicatePrimaryKeyException(Table.java:636)
    at io.realm.internal.Table.addEmptyRowWithPrimaryKey(Table.java:408)
    at io.realm.Realm.createObject(Realm.java:678)
    at io.realm.IngredientTypeRealmProxy.copy(IngredientTypeRealmProxy.java:300)
    at io.realm.IngredientTypeRealmProxy.copyOrUpdate(IngredientTypeRealmProxy.java:295)     at io.realm.IngredientRealmProxy.copy(IngredientRealmProxy.java:470)
    at io.realm.IngredientRealmProxy.copyOrUpdate(IngredientRealmProxy.java:451)
    at io.realm.DefaultRealmModuleMediator.copyOrUpdate(DefaultRealmModuleMediator.java:208)
    at io.realm.Realm.copyOrUpdate(Realm.java:1166)
    at io.realm.Realm.copyToRealm(Realm.java:697)
    at io.realm.Realm.copyToRealm(Realm.java:735)
    at team.jcandfriends.namnam.ui.HardRefreshActivity$1.onNext(HardRefreshActivity.java:152)
    at rx.observers.SafeSubscriber.onNext(SafeSubscriber.java:139)
    at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.pollQueue(OperatorObserveOn.java:202)
    at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber$2.call(OperatorObserveOn.java:162)
    at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5294)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)

我的问题是为什么发生这种情况时,我首先使用realm.getTable(Recipe.class).clear()删除了所有对象,因此我认为使用realm.copyToRealm(list)已经安全了,因为该表已经为空。我很抱歉我的无知,我喜欢领域,就像真的一样:)

我从这里获取数据:https://namnamnam.herokuapp.com/api/recipes

1 个答案:

答案 0 :(得分:0)

你应该试试这个

realm.executeTransaction(new Realm.Transaction() {
    @Override
    public void execute(Realm realm) {
        realm.where(Recipe.class).findAll().deleteAllFromRealm();
        realm.insertOrUpdate(list);
    }
});