I'm having an issue that I can't find any documentation for with Room for Android and auto generating the primary key.
I've got an entity class that looks sort of like this:
@Entity
public class Preference {
@PrimaryKey(autoGenerate = true)
private int id;
public void setId(int id) {
this.id = id;
}
}
This is working fine when I've set the id manually but when I don't set the primary key I'm getting an error regarding the primary key being null. Looking at the autogenerated file I can't see anywhere that it would auto increment the primary key.
So I guess my question is this: can you auto generate a primary key of a private member with a setter or would I need to manually auto generate my key in the setter?
Okay, so this code won't generate the id member due to the member being null I either have to set it as an Integer object, in which case it will autogenerate a new id when the member is equal to null, or, I need to set it to be equal to 0 on initialising the object which will do the same.
I've set it to an Integer which fixes my issue perfectly.
@Entity
public class Preference {
@PrimaryKey(autoGenerate = true)
private Integer id;
public void setId(Integer id) {
this.id = id;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With