5

Following code is not resetting/clearing the auto increment id to 0

database = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, DatabaseMeta.DB_NAME)
            .build();
database.query("DELETE FROM sqlite_sequence WHERE name = ?", new Object[]{"tableName"});

or

database.query("REPLACE INTO sqlite_sequence (name, seq) VALUES ('mission', -1)", null);

Is there anyway to clear sqlite_sequence in Android room?

Android room is not using "sqlite_sequence" for auto increment logic i think, not sure. Tried printing sqlite_sequence entries, can't find the table name i used(which has the auto increment primary key).

uday
  • 1,348
  • 12
  • 27

3 Answers3

1

The algorithm for determening the rowid when AUTOINCREMENT is used, and thus when sqlite_sequence is created/used, uses the higher of the highest existing rowid or the value (seq column) in the sqlite_sequence table.

As such if any rows exist in the associated table then setting the seq column will have no effect if it is not a value greater than the highest rowid in the associated table.

If the table has no rows then I believe that dropping the table will result in the respective row in the sqlite_sequence table being removed automatically.

MikeT
  • 51,415
  • 16
  • 49
  • 68
1

Try this code works for me

class FeedReaderDbHelper extends SQLiteOpenHelper {
    static final int DATABASE_VERSION = 1;
    static final String DATABASE_NAME = DBConfig.DATABASE_NAME;

    FeedReaderDbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    public void onCreate(SQLiteDatabase db) {
    }

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        onCreate(db);
    }

    public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        onUpgrade(db, oldVersion, newVersion);
    }
}

FeedReaderDbHelper mDbHelper = new FeedReaderDbHelper(mainContext.getApplicationContext());
mDbHelper.getWritableDatabase().execSQL("DELETE FROM sqlite_sequence WHERE name='table_name';");
byteC0de
  • 5,153
  • 5
  • 33
  • 66
  • 1
    Seems Android room wont support on clearing sqlite_sequence, which is explained in https://stackoverflow.com/a/53764393/3442067. Have to create our own SQLiteOpenHelper to clear or modify sqlite_sequence table. – uday Jan 20 '20 at 10:30
1

I put this function in my RoomDatabase class:

        companion object {

    fun resetPointer(nonRoomDb: MyRoomDatabase){

      nonRoomDb.openHelper.writableDatabase.execSQL("DELETE FROM sqlite_sequence")

}       
}

So you can call it everywhere in code:

    val database = MyRoomDatabase.getInstance(application)

    MyRoomDatabase.resetPointer(database)
Reyhane Farshbaf
  • 453
  • 6
  • 12