Android room migration new table

When you need to add a new table to an existing Android Room database, you'll need to follow these steps:

  1. Update your database schema: In your @Database annotation, add the new table to the entities array. For example:

    @Database(entities = [User::class, Address::class, NewTable::class], version = 2)
    abstract class MyDatabase : RoomDatabase() {
     //...
    }

    In this example, we're adding a new table called NewTable to the database schema.

  2. Create the new table entity: Create a new Kotlin class that represents the new table. This class should be annotated with @Entity and have the necessary fields and relationships:

    @Entity
    data class NewTable(
     @PrimaryKey(autoGenerate = true) val id: Long,
     val name: String,
     @ColumnInfo(name = "created_at") val createdAt: Date
    )
  3. Update your DAO: Update your DAO interface to include the new table. You can do this by adding a new method that returns a LiveData or a Flowable of the new table:

    @Dao
    interface MyDao {
     //...
    
     @Query("SELECT * FROM new_table")
     fun getNewTable(): LiveData<List<NewTable>>
    
     //...
    }
  4. Migrate the database: When you run your app for the first time, Room will automatically migrate the database to the new schema. You can also use the RoomDatabase.Builder to specify a migration strategy:

    val db = Room.databaseBuilder(context, MyDatabase::class.java, "my_database")
    .addMigrations(MIGRATION_1_2)
    .build()

    In this example, we're specifying a migration from version 1 to version 2.

  5. Handle the migration: In your migration strategy, you'll need to update the database schema to include the new table. You can do this by creating a new migration class that extends Migration:

    class Migration_1_2 : Migration(1, 2) {
     override fun migrate(database: SupportSQLiteDatabase) {
         database.execSQL("CREATE TABLE new_table (_id INTEGER PRIMARY KEY, name TEXT, created_at INTEGER)")
     }
    }

    In this example, we're creating a new table called new_table with the specified columns.

That's it! With these steps, you should be able to add a new table to your Android Room database.