Search code examples
androidrealm

How do I set a unique primary key in Realm?


How do I set a unique primary key in Realm in Android? The Realm documentation says I cannot use anything but String or int/long, so is UUID type is out of the question too? What if I have items with the same name?

e.g.

public class GroceryItem extends RealmObject {
    @PrimaryKey
    private long        id;    <--- how can I make this unique without UUID?
    private String      name;

public long getId() {
    return id;
}
public void setId(long id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
} }

Solution

  • Realm doesn't support any autoincrement for primary keys. Visit docs for more information about this. So, you are to handle it by yourself.

    1) Use should use UUID. You can also get long, int or String value from it:

    long: UUID.randomUUID().getMostSignificantBits();
    int: (int) UUID.randomUUID().getMostSignificantBits();
    String: UUID.randomUUID().toString();
    

    2) Or you can query some data from your database and apply some rules to generate a new key. For example, query for the last element and increment it's primarykey. But that's not ideal way.