Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Room - Autogenerate Primary Key

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?

like image 202
James Lendrem Avatar asked Sep 08 '17 09:09

James Lendrem


1 Answers

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;

    }

}
like image 102
James Lendrem Avatar answered Sep 28 '22 02:09

James Lendrem