How to set primary key auto increment in realm android

Maaz Patel picture Maaz Patel · Oct 21, 2016 · Viewed 38.7k times · Source

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.

Answer

EpicPandaForce picture EpicPandaForce · Oct 21, 2016

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