Reset auto-increment in Android's Room library

允我心安 提交于 2019-12-23 05:59:20

问题


I created a table using Android's Room library, which stores items of type User. For the ID column, the value is automatically generated by adding the annotation

@PrimaryKey(autoGenerate = true)

In the next application run, I delete all entries in the table. However, the auto-generated value is not reset to 0, but continues where it left of the previous run.

How can I reset the auto-increment counter when I delete all entries in a table?


回答1:


Why would you, is perhaps the more pertinent question. A column with AUTOINCREMENT will be an alias of the rowid column which is used to uniquely identify a row. It isn't the best practice to rely upon this value other than for identifying a row.

Using AUTOINCREMENT (autogenerate = true) results in an internal table sqlite_sequence being created, a row in that table holds the value of the highest ever used rowid The next rowid will be that values + 1. Hence your issue.

As such to restart from 1 you would have to either update the respective row in the sqlite_sequence table to 0 or delete the respective row in the sqlite_sequence table.

You may wish to have a look at Android Room - reset auto generated key on each app run. Noting that this could be the basis for resetting the sequence value, but that it will always resets the sequence value.



来源:https://stackoverflow.com/questions/53805597/reset-auto-increment-in-androids-room-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!