Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Room Android - How to handle database version upgrade

I am reading about Android Architecture components Room and wanted to know if there is there anything in Room equivalent to onUpgrade in SQLiteOpenHelper method available.

@Override
 public void onUpgrade(final SQLiteDatabase database, final int oldVersion, final int newVersion) {}
like image 575
RS_Mob Avatar asked Jan 11 '18 10:01

RS_Mob


People also ask

Is room database deprecated?

This field is deprecated.

How do I move a room DB?

You can use AutoMigrationSpec to give Room the additional information that it needs to correctly generate migration paths. Define a static class that implements AutoMigrationSpec in your RoomDatabase class and annotate it with one or more of the following: @DeleteTable. @RenameTable.

Why should I migrate from SQLite to room database in Android?

The Room persistence library provides a number of benefits over using the SQLite APIs directly: Compile-time verification of SQL queries. Convenience annotations that minimize repetitive and error-prone boilerplate code.

What is the difference between SQLite and room database in Android?

Room vs SQLite Room provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite. In the case of SQLite, There is no compile-time verification of raw SQLite queries. But in Room, there is SQL validation at compile time.


1 Answers

You can use https://developer.android.com/training/data-storage/room/migrating-db-versions.html

 Room.databaseBuilder(getApplicationContext(), MyDb.class, "database-name")
            .addMigrations(MIGRATION_1_2,MIGRATION_1_3, MIGRATION_2_3).build();

    static final Migration MIGRATION_1_2 = new Migration(1, 2) {
        @Override
        public void migrate(SupportSQLiteDatabase database) {
            database.execSQL("CREATE TABLE `Fruit` (`id` INTEGER, "
                    + "`name` TEXT, PRIMARY KEY(`id`))");
        }
    };

    static final Migration MIGRATION_2_3 = new Migration(2, 3) {
        @Override
        public void migrate(SupportSQLiteDatabase database) {
            database.execSQL("ALTER TABLE Book "
                    + " ADD COLUMN pub_year INTEGER");
        }
    };

   static final Migration MIGRATION_1_3 = new Migration(1, 3) {
            @Override
            public void migrate(SupportSQLiteDatabase database) {
                database.execSQL("ALTER TABLE Book "
                        + " ADD COLUMN pub_year INTEGER");
            }
        };
like image 61
MJM Avatar answered Sep 17 '22 17:09

MJM