5

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

1 Answer 1

8

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.

3
  • This is it, thanks Potapov. I also like the suggestion on how to overcome auto increment; what would you say is the ideal way?
    – Xarsiss
    Aug 9, 2017 at 10:11
  • Well, an ideal way is just to use UUID and generate it randomly Aug 9, 2017 at 11:25
  • Oh I see thanks, I thought you meant there was a better way to implement auto increment :-) I misread, thanks again & have a good day.
    – Xarsiss
    Aug 9, 2017 at 13:44

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.