简体   繁体   中英

Primary key value must not be null. Realm

I have weird issue using Realm, I'm new in it. My model has @PrimaryKey private String id; field, when I trying to save model into realm my app crashes with this exception.

11-25 10:14:55.014 22175-22175/? D/myTag: false
java.lang.IllegalArgumentException: Primary key value must not be null.

Model has name Run, here is how I use it.

@Override
public void add(Run run) {
    realm.beginTransaction();

        int lastId;
        RealmResults<Run> all = realm.where(Run.class).findAll();
        if(all.isEmpty())
            run.setId("0");
        else {
            lastId = Integer.parseInt(all.last().getId());
            run.setId(String.valueOf(lastId + 1));
        }
        Log.d("myTag",""+(run.getId()==null));
        realm.copyToRealmOrUpdate(run);

    realm.commitTransaction();
}

My model:

public class Run extends RealmObject {
@PrimaryKey
private String id;
private long activeShiftId;
private long storeId;
private int runState;
private RealmList<Order> orders;
private double totalRevenue;
private double creditRevenue;
private long estimatedTime;
...
}

Log says false. What am I doing wrong?

java.lang.IllegalArgumentException: Primary key value must not be null.

Solve this problem, I forget about my collection inside my Run model, set id to every item and it works now.

If you have collection of RealmObject in your RealmObject, you should set id(primary key) to every item in that collection and set primary key to external model's field.

From the given code snippet I can guess that, in your model, Id is a primary key field(which should not be null by default). that is why it is raising the error.

this line is setting it to null-

  run.setId("0");

try to modify this line according to your program logic.

As of Realm 0.89.0 field, annotated with @PrimaryKey , could be null. See CHANGELOG .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM