Search code examples
android-studioauto-generate

Android Studio: How do i let the room database autogenerate ID for records?


I have this as the class where I want to let Room autogenerate ID.

@Entity(tableName = "mitglieder_table")
public class Mitglieder {

    @PrimaryKey(autoGenerate = true)
    private int id;

    @ColumnInfo(name = "Vorname")
    private String vorname;

    @ColumnInfo(name = "Nachname")
    private String nachname;

    public String getVorname() {
        return vorname;
    }

    public void setVorname(String vorname) {
        this.vorname = vorname;
    }

    public String getNachname() {
        return nachname;
    }

    public void setNachname(String nachname) {
        this.nachname = nachname;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public Mitglieder(String vorname, String nachname) {
        this.vorname = vorname;
        this.nachname = nachname;
    }
}

The private int id is just used for the getter and setter.

Is this already enough to autogenerate ID or do i have to mention it in other classes? Do I have to include id in the constructor?

Thanks guys for your help.


Solution

  • This is enough, the ID will be auto-generated, you don't have to include it in your constructor. If in the future you want to use any other constructor, you can declare it and annotate it with @Ignore and Room will ignore it.