Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set a unique primary key in Realm?

Tags:

android

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;
} }
like image 463
Xarsiss Avatar asked Jan 29 '23 20:01

Xarsiss


1 Answers

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.

like image 152
Anton Potapov Avatar answered Feb 03 '23 07:02

Anton Potapov