How to set primary key auto increment in realm android

后端 未结 8 619
眼角桃花
眼角桃花 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:43

    This is an old and already answered question, but I want to post another solution that I used. You can do like this:

    Realm realm = Realm.getDefaultInstance();
    // Realm transaction
    realm.executeTransactionAsync(new Realm.Transaction() { 
        @Override
         public void execute(Realm bgRealm) {
             // Get the current max id in the users table
             Number maxId = bgRealm.where(users.class).max("id");
             // If there are no rows, currentId is null, so the next id must be 1
             // If currentId is not null, increment it by 1
             int nextId = (maxId == null) ? 1 : maxId.intValue() + 1;
             // User object created with the new Primary key
             users user = bgRealm.createObject(users.class, nextId);
             // Now you can update your object with your data. The object will be
             // automatically saved in the database when the execute method ends
             // ...
             // ... 
        }
    }
    

提交回复
热议问题