Sathyan
Sathyan

Reputation: 168

How to change Entity class Fileds in Room Database in Android

In my project, I am storing Data into local database.For that I am using Room Library. As per the android documentation I've created One Entity class,One abstract Database class,One Dao interface.I have successfully stored and retrieved data.

But now I want to add one field in Entity(Model Class). After updating that class and while i am saving data in database, it is crashing. It shows some error in Dao_Impl class.Actually it is an auto generated class.How do I solve this error?

Can anyone help me to solve this issue? Thanks in Advance.

Upvotes: 0

Views: 604

Answers (2)

Anisuzzaman Babla
Anisuzzaman Babla

Reputation: 7480

For any change in Data manipulation language (DML) like Table Structure you must provide a migration strategy

Room.databaseBuilder(getApplicationContext(), MyDb.class, "YOUR_DATABASE_NAME")
    .addMigrations(MIGRATION_1_2).build();

static final Migration MIGRATION_1_2 = new Migration(1, 2) {
    @Override
    public void migrate(SupportSQLiteDatabase database) {
        database.execSQL("ALTER TABLE YOUR_TABLE_NAME ADD COLUMN YOUR_NEW_COLUMN_NAME TEXT");
    }
};

Here 1 is your old database version and 2 is the current database version. Don't forget to add field to your entity class.

Upvotes: 1

Mohsen
Mohsen

Reputation: 1389

you need to write migration for your database. follow https://developer.android.com/training/data-storage/room/migrating-db-versions

Upvotes: 0

Related Questions