How to set primary key auto increment in realm android

后端 未结 8 572
眼角桃花
眼角桃花 2020-12-14 07:13

I want to set primary key auto increment for my table.

Here is my Class. I have set primary key but I want it to be auto increment primary key.

publ         


        
8条回答
  •  有刺的猬
    2020-12-14 07:49

    In a transaction, you can always reliably access the current maximum ID, based on which you can increment that and use it as the basis for the next ID.

     realm.executeTransaction(new Realm.Transaction() { // must be in transaction for this to work
         @Override
         public void execute(Realm realm) {
             // increment index
             Number currentIdNum = realm.where(users.class).max(usersFields.ID);
             int nextId;
             if(currentIdNum == null) {
                nextId = 1;
             } else {
                nextId = currentIdNum.intValue() + 1;
             }
             users user = new users(); // unmanaged
             user.setId(nextId);
             //...
             realm.insertOrUpdate(user); // using insert API
         }
     }
    

提交回复
热议问题