16

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?

James Lendrem
  • 1,780
  • 2
  • 15
  • 23

1 Answers1

17

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;

    }

}
James Lendrem
  • 1,780
  • 2
  • 15
  • 23
  • 1
    @ghosh I've added it into the answer above. Instead of using the base type int you need to use the Integer class instead. – James Lendrem Jun 07 '18 at 10:30
  • Cheers I did figure that out. I'm using the generated key as sort-of ticket in a queue. I'm having trouble getting it to start at 1 at every app run. clearAllTables doesn't help.. – Eggcellentos Jun 08 '18 at 09:07
  • 1
    No worries. The problem you are having is that while 'clearAllTables' deletes the information in the table it doesn't reset the auto_increment id in the process. I'm not sure if Room has this ability inbuilt but you can do it by running a query in Room using: 'ALTER TABLE tablename AUTO_INCREMENT = 1'. Bear in mind that this will reset the index but not delete the data. – James Lendrem Jun 08 '18 at 12:16
  • I did try that before, Room doesn't directly support it. I attempted a RawQuery to try and inject the command, no success, mostly 'bad syntax' errors or just nothing happens.. I'll keep at it thanks alot – Eggcellentos Jun 08 '18 at 12:20
  • Do you have the error, I might be able to help with it a bit further? – James Lendrem Jun 08 '18 at 12:29
  • I'm AFC(away from code :)) I'll post it start of week – Eggcellentos Jun 08 '18 at 12:55
  • https://stackoverflow.com/questions/50878734/room-reset-auto-generated-key-on-each-app-run – Eggcellentos Jun 15 '18 at 15:35