How to set primary key auto increment in realm android

烂漫一生 提交于 2019-12-18 12:47:42

问题


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.

public class users extends RealmObject {

@PrimaryKey
private int id;
private long icn;
private String name;
private String email;
private String password;
private int phone;

public String getName() {
    return name;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public long getIcn() {
    return icn;
}

public void setIcn(long icn) {
    this.icn = icn;
}

public void setName(String name) {
    this.name = name;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public int getPhone() {
    return phone;
}

public void setPhone(int phone) {
    this.phone = phone;
}

}

Thanks in Advance.


回答1:


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
     }
 }



回答2:


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
         // ...
         // ... 
    }
}



回答3:


Well, @PrimaryKey is only indicates that field is a key. But you set it yourself when creating object and copying it to Realm. Consider using UUID.random(), ot increment it manually. (as in answer from comment): Realm Auto Increament field example




回答4:


there is an example that make a sequence to implement auto increment of primary key id:

https://raw.githubusercontent.com/505aaron/realm-migration-example/master/realm/sequencer.js

const sequencer = (realmInstance, schema, props) => new Promise((resolve, reject) => {
  let saved;

  try {
    realmInstance.write(() => {
      const obj = { ...props };

      if (typeof obj.id === 'undefined') {
        let seq = realmInstance.objects('Sequence').filtered(`name = "${schema}"`)[0];
        if (typeof seq === 'undefined') {
          seq = realmInstance.create('Sequence', { name: schema, value: 0 });
        }
        obj.id = seq.next();
      }
      saved = realmInstance.create(schema, obj, true);

      resolve({ ...saved });
    });
  } catch (e) {
    reject(e);
  }
});

export default sequencer;



回答5:


For react native

...
// this is the part where you are saving the newItem
realm.write(() => {
    // handle the id
    let id: any = realm.objects(this.Schema).max("id");
    newItem.id = id === undefined ? 1 : id++;
    realm.create(this.Schema, newItem);
    resolve(newItem);
});



回答6:


In Kotlin

My Interfaces

fun getRegistroIdentity(): Int

My Method

class RegistroOver(private val realm: Realm) : RegistroImplementation {

override fun getRegistroIdentity(): Int {
    val registro = realm.where(Registro::class.java).max("id")
    val result: Int
    result = if (registro == null) {
        1
    } else {
        registro.toInt() + 1
    }
    return result
}}

:)




回答7:


A shorter answer can be something like this:

    Person person = new Person();
    person.setName("UserName");

    realm.beginTransaction();

    Number newId = realm.where(Person.class).max("id");
    person.setId(newId.intValue()+1);

    realm.copyToRealm(person);
    realm.commitTransaction();



回答8:


In my personal case, I set id as Unix time value. I know isn't increment but is unique 🙃

(int) System.currentTimeMillis() / 1000;


来源:https://stackoverflow.com/questions/40174920/how-to-set-primary-key-auto-increment-in-realm-android

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!