33

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.

Abhishek Patel
  • 4,280
  • 1
  • 24
  • 38
Maaz Patel
  • 756
  • 2
  • 7
  • 20
  • 1
    Possible duplicate of [Realm Auto Increament field example](http://stackoverflow.com/questions/31229226/realm-auto-increament-field-example) – R. Zagórski Oct 21 '16 at 11:03
  • I am looking for in built property in realm which will automatically increment like other database. – Maaz Patel Oct 21 '16 at 11:33
  • You won't find that because it doesn't exist. Mostly because it can be done in 6 lines without much effort, so it was never a high priority. – EpicPandaForce Oct 21 '16 at 11:36
  • Realm is object database - it stores a graph of objects. Tables uses primary keys when indexing tables, there is no such a thing, Realm uses @PrimaryKey for indexing convenience – Alex Shutov Oct 21 '16 at 11:37
  • @AlexShutov well, primary keys are important to identify objects in order to update them later, and rather important for the newly released Realm Object Server's synchronization logic. But what you set as primary key is pretty much up to you. – EpicPandaForce Oct 21 '16 at 11:38

9 Answers9

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
     }
 }
EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
  • 1
    BTW this is a bit trickier for Synchronized Realm's where it is typically better to use a random UUID instead. Or a RealmCounter when it will be supported. – EpicPandaForce May 20 '17 at 22:35
  • @EpicPandaForce how do you go about this when writing JSON directly into realm and you want to auto generate the primary key values? it would be nice if you could just ad a second annotation like RealmAutoGenerate – Hector Nov 15 '18 at 12:20
  • You probably can't do that automatically if you use the `createAllFromJson` and such methods. – EpicPandaForce Nov 15 '18 at 13:34
12

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
         // ...
         // ... 
    }
}
Federico Mastrini
  • 724
  • 11
  • 15
4

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

Community
  • 1
  • 1
Alex Shutov
  • 3,217
  • 2
  • 13
  • 11
  • 1
    sorry, copied address of wrong tab: http://stackoverflow.com/questions/31229226/realm-auto-increament-field-example – Alex Shutov Oct 21 '16 at 11:35
2

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

:)

Irvin Joao
  • 1,010
  • 8
  • 8
1

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;
bibodeng
  • 13
  • 1
  • 7
1

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();
iman kazemayni
  • 1,255
  • 1
  • 19
  • 20
0

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);
});
lukaserat
  • 4,768
  • 1
  • 25
  • 36
-1

i use this.

public static int nextID(Class table) {
        return instance.realm.where(table).findAll().max("id").intValue() + 1;
    }

So i i want to increment Class Person Id,

netID(Person.class);
hamil.Dev
  • 137
  • 2
  • 9
-3

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

(int) System.currentTimeMillis() / 1000;
Moises Portillo
  • 828
  • 8
  • 12