Ravi
Ravi

Reputation: 35589

Room cannot verify the data integrity

I am getting this error while running a program with Room Database

Room cannot verify the data integrity. Looks like you've changed schema but forgot to update the version number. You can simply fix this by increasing the version number.

It seems we need to update Database version, but from where can we do that in Room?

Upvotes: 156

Views: 137514

Answers (26)

Hassan Wasfy
Hassan Wasfy

Reputation: 1

I have got the solution, I faced this issue and the problem was based on how the room works, I did find that room doesn't apply the Migration initially , but it keens on the Room database call back,

so as you can see in next code snippets :

the old code is :

@Database(entities = [User::class], version = 4, exportSchema = true)
abstract class AppDatabase : RoomDatabase() {
    abstract fun userDao(): UserDao

    companion object {
        private var dbInstance: AppDatabase? = null

        fun getInstance(appContext: Context): AppDatabase {
            if (dbInstance != null) {
                return dbInstance as AppDatabase
            }

            dbInstance = Room.databaseBuilder(appContext, AppDatabase::class.java, "Sample.db")
                .createFromAsset("database/myapp.db", Setup())
                .addMigrations(object : Migration(0, 1) {
                    override fun migrate(db: SupportSQLiteDatabase) {
                        db.execSQL("ALTER TABLE user ADD COLUMN email TEXT;")
                    }
                }, object : Migration(1, 2) {
                    override fun migrate(db: SupportSQLiteDatabase) {
                        db.execSQL("ALTER TABLE user ADD COLUMN age TEXT;")
                    }
                }, object : Migration(2, 3) {
                    override fun migrate(db: SupportSQLiteDatabase) {
                        db.execSQL("ALTER TABLE user ADD COLUMN birthDate TEXT DEFAULT 'H';")
                    }
                }, object : Migration(3, 4) {
                    override fun migrate(db: SupportSQLiteDatabase) {
                        db.execSQL("CREATE TABLE TEST (id INTEGER PRIMARY KEY, name TEXT)")
                    }
                })
                .build()
            Log.i("Key_Key", "Data base created successfully.")
            dbInstance!!.openHelper.writableDatabase
            return dbInstance as AppDatabase
        }
    }
}

this if you wanted to add columns like email, age, birthDay, or even add a new whole table.

this code is not going to work at all.

as the room will not see the updates for the first time,

all what you need is only setting up the room call back:

so be something like :

class Setup : RoomDatabase.PrepackagedDatabaseCallback() {
    override fun onOpenPrepackagedDatabase(db: SupportSQLiteDatabase) {
        super.onOpenPrepackagedDatabase(db)
        db.execSQL("ALTER TABLE user ADD COLUMN email TEXT;")
        db.execSQL("ALTER TABLE user ADD COLUMN age TEXT;")
        db.execSQL("ALTER TABLE user ADD COLUMN birthDate TEXT DEFAULT 'Y';")
        db.execSQL("CREATE TABLE TEST (id INTEGER PRIMARY KEY, name TEXT)")
    }
}

and you are ready to go.

i think there is more space to improve this solution , but till now we are so far so good.

happy coding 👍🏻 💯

Upvotes: 0

Seán
Seán

Reputation: 1

In Android, if you changed the Room code, in any of the scripts, when you run the app, the DB sops working. The solution that I always use, is to uninstall the application in the emulator and reinstall it. With this, the DB Room is properly updated and it works.

Upvotes: -1

Try_Except
Try_Except

Reputation: 1

Go to the Google Drive app on your device > More options > Backups > Delete the last saved backup.

After that, uninstall and reinstall your application.

Upvotes: 0

Piyush Apkaje
Piyush Apkaje

Reputation: 31

For an easy solution, in Android Studio, go to Device Explorer (formerly Device File Explorer), go to /data/data/<your package name>/databases, and delete all the files.

This is useful during development, before your tables are finalized.

Upvotes: 2

methodsignature
methodsignature

Reputation: 4412

When you first come across this message, you will most likely be working against an unreleased version of the database. If that is the case, most likely you should not increment the database version. Simply clearing app data will move you passed the exception. If your app is live, you will likely need to increment the database version and provide a proper migration.

If you do not increment the database (recommended):

You should clear the application's app data from Android settings. You might alternatively be able to uninstall the previous app version and then install the new version to get passed the exception. This latter approach does not work under certain conditions (such as when allow backup is enabled)

Since clearing application data always works, I take that route every time.

If you do increment the database version:

You will need to write database migration code to account for any changes to the database schema. See here for information on migration.

Alternative to writing database migration code is to call fallbackToDestructiveMigration on the Room database builder. This is probably not a good idea as this change should not be published to actual users. Forgetting to remove this call and then forgetting to upgrade the database will result in data loss for users.

// Using this fallback is almost certainly a bad idea
Database database = Room.databaseBuilder(context, Database.class, DATABASE_NAME)
        .fallbackToDestructiveMigration()
        .build();

Again, neither incrementing the database version nor falling back to destructive migration is necessary if the previous database schema is not live in the wild.

Upvotes: 218

Afshin Samiei
Afshin Samiei

Reputation: 129

If you have this problem in development process and you have not released your application yet you don't have to increase your database version because it's not meaningful when your app is not live yet.

This problem refers to Room if you are pre-populating your database with a database file in asset folder.

Room will create a master table that holds a hash code in it to manage your migrations and it will check the code with the generated code in your application database therefore you need to remove this table from your initial database and replace it with the current initial database in the asset folder:

remove room master table

remove this!

enter image description here

replace here!

After that clear your application data from

setting->App->(your application)->storage->clear data

then reinstall the application.

this works!

Upvotes: 0

Rahman Rezaee
Rahman Rezaee

Reputation: 2165

Because You Changed the Column of tables shows this error two ways to solve

  1. Just Remove the app and run it again

  2. upgrade the version of the database

    @Database(
         entities = [BatteryED::class],
         version = 2, // increase the number
         exportSchema = false
    )
    
    abstract class TestDatabase : RoomDatabase() ...
    

Upvotes: 1

Aniruddh Parihar
Aniruddh Parihar

Reputation: 3100

Its Very simple as shown in log

Looks like you've changed schema but forgot to update the Database version number. 
You can simply fix this by increasing the version number.

Simple go to your Database Version class and upgrade your DB version by increasing 1 from current.

For Example : Find @Database annotation in your project like below

@Database(entities = {YourEntityName.class}, version = 1)

Here version = 1, is database version, you have to just increase it by one, That's it.

Upvotes: 24

Marci
Marci

Reputation: 969

Do not use this solution in production code!
Use Aniruddh Parihar's answer, or peterzinho16's answer instead!

On android phone:

Uninstall the app or Clear app data

To delete app data: Go settings -> Apps -> Select your app -> Storage -> Clear data

The uninstall (and re-install) not works in every case, so try clear data first!

Upvotes: 19

Samir
Samir

Reputation: 6617

Fast Solution

Go to AddDatabase Class and increase your db version

import androidx.room.Database
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase

@Database(entities = arrayOf(Product::class, SatisNok::class), version = 6)
abstract class AppDatabase : RoomDatabase() {
    abstract fun productDao(): ProductDao
    abstract fun satisDao(): SatisNokDao
}

Go to Activity or where you call your db

add the method of migration, here I changed the version from 5 to 6

  val MIGRATION_1_2: Migration = object : Migration(5,6) {
            override fun migrate(database: SupportSQLiteDatabase) {
                // Since we didn't alter the table, there's nothing else to do here.
            }
        }

Now add the migration addition to your db builder as .addMigrations(MIGRATION_1_2)

 val db = Room.databaseBuilder(
                applicationContext,
                AppDatabase::class.java, "supervisor"
            ).fallbackToDestructiveMigration()
                .allowMainThreadQueries()
                .addMigrations(MIGRATION_1_2)
                .build()

For more details you may wish to look at here its getting more complicated day by day where they should provide easier solitions.

after operation you may comment line the //.addMigrations(MIGRATION_1_2) and keep it for the next time

Upvotes: 0

peterzinho16
peterzinho16

Reputation: 989

In order to fix the problem in kotlin:

First

@Database(entities = [Contact::class], version = 2)

Second

val MIGRATION_1_2 = object : Migration(1, 2) {
        override fun migrate(database: SupportSQLiteDatabase) {
            database.execSQL("ALTER TABLE Contact ADD COLUMN seller_id TEXT NOT NULL DEFAULT ''")
        }
    }

Third

private fun buildDatabase(context: Context) = Room.databaseBuilder(
            context.applicationContext,
            EpayDatabase::class.java,
            "epay"
        )
            .addMigrations(MIGRATION_1_2)
            .build()

For more details, check the official documentation

Upvotes: 10

Gavin Wright
Gavin Wright

Reputation: 3212

In my case I was making an update to a database that I'll be pre-packaging with my app. None of the suggestions here worked. But I finally figured out that I could open the .db file in a database program (I used "DB Browser for SQLite"), and manually change the "User version" from 2 back to 1. After that, it worked perfectly.

I guess any update you make changes this user version, and this is why I kept getting this error.

Upvotes: 0

Willey Hute
Willey Hute

Reputation: 1088

I got the same error during the training program of Codelabs. Where In one training session I created a project and it ran successfully with all database operations. In the next session, I was working with a different repo, but it was an extension of the previous project, From the first build of the extended app only I had got the error.

Maybe Studio keeps authentication techniques with room database that's missing with the new build.

Upvotes: -2

Hagar Magdy
Hagar Magdy

Reputation: 313

If increasing schema version didn't work with you, provide migration of your database. To do it you need to declare migration in database builder:

Room.databaseBuilder(context, RepoDatabase.class, DB_NAME)
  .addMigrations(FROM_1_TO_2)
.build();

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

Upvotes: 2

Rajeev Shetty
Rajeev Shetty

Reputation: 1784

@Database(entities = {Tablename1.class, Tablename2.class}, version = 3, exportSchema = false)

Change the version number in your RoomDatabase class. Increment the version number.

Upvotes: 2

Keshav Gera
Keshav Gera

Reputation: 11264

1:- It seems we need to update database version (increment by 1)

enter image description here

2nd Uninstall the app or Clear app data

Upvotes: 9

live-love
live-love

Reputation: 52514

android:allowBackup="true" inside AndroidManifest.xml prevents the data from being cleared even after the app is uninstalled.

Add this to your manifest:

android:allowBackup="false"

and reinstall the app.

Note: Make sure you change it back to true later on if you want auto backups.

Another solution:

Check the identityHash of your old json file and the new json file in apps\schema folder.

If the identityHash is different, it will give that error. Find out what you have changed by comparing both json files if you don't want to change anything.

Make sure you have exportSchema = true.

@Database(entities = {MyEntity.class, ...}, version = 2, exportSchema = true)

json schema file:

  "formatVersion": 1,
  "database": {
    "version": 2,
    "identityHash": "53cc5ef34d2ebd33c8518d79d27ed012",
    "entities": [
      {

code:

private void checkIdentity(SupportSQLiteDatabase db) {
    String identityHash = null;
    if (hasRoomMasterTable(db)) {
        Cursor cursor = db.query(new SimpleSQLiteQuery(RoomMasterTable.READ_QUERY));
        //noinspection TryFinallyCanBeTryWithResources
        try {
            if (cursor.moveToFirst()) {
                identityHash = cursor.getString(0);
            }
        } finally {
            cursor.close();
        }
    }
    if (!mIdentityHash.equals(identityHash) && !mLegacyHash.equals(identityHash)) {
        throw new IllegalStateException("Room cannot verify the data integrity. Looks like"
                + " you've changed schema but forgot to update the version number. You can"
                + " simply fix this by increasing the version number.");
    }
}

Upvotes: 67

Daniel Jonker
Daniel Jonker

Reputation: 854

I just had a similar issue in an espresso test and the only thing that fixed it was clearing data and also uninstalling the androidx test apks like:

adb uninstall androidx.test.orchestrator
adb uninstall androidx.test.services

Upvotes: 1

Hitesh Sahu
Hitesh Sahu

Reputation: 45160

By default Android manifest have android:allowBackup="true", Which allow apps to persist their SQLite DB on reinstallation.

Suppose your DATABASE_VERSION was initially 3 and then you decide to reduce DB version from 3 to 1.

@Database(entities = {CallRecording.class}, version = DATABASE_VERSION)
public abstract class AppDatabase extends RoomDatabase {
    public abstract RecordingDAO recordingDAO();

//    static final Migration MIGRATION_1_2 = new Migration(1, 2) {
//        @Override
//        public void migrate(SupportSQLiteDatabase database) {
//            // Since we didn't alter the table, there's nothing else to do here.
//        }
//    };
}

You can achieve it like this

  • Clear App data from Setting. This will remove older DB(DATABASE_VERSION =3)from phone
  • Uninstall your App
  • Reduce DATABASE_VERSION version to 1
  • Build and Reinstall Your App

Its a good practise to keep DATABASE_VERSION as constant.

Upvotes: 38

Divyanshu Negi
Divyanshu Negi

Reputation: 602

In my case android:allowBackup="false" making it from true to false worked, as this has given me nightmares before as well, this is the weirdest thing why is this setting enabled by default!

Upvotes: 8

Extremis II
Extremis II

Reputation: 5603

This issue occurs mostly in development.

If you change your schema i.e., rename/add/modify your class containing table entity the integrity between exiting db in your previous build conflicts with new build.

clear the app data or install new build after uninstalling the previous build.

Now, The old db won't conflict with the newer one.

Upvotes: 5

Harry .Naeem
Harry .Naeem

Reputation: 1331

In my case I had an AppDatabase class.

@Database(entities = {GenreData.class, MoodData.class, SongInfo.class,
    AlbumsInfo.class, UserFolderListsData.class, UserPlaylistResponse.PlayLists.class, InternetConnectionModel.class}, version = 3, exportSchema = false)

I updated this version number and it solved the problem. Problem arose because i had added a property in SongInfo class and forgot to update the version number.

Hope it helps someone.

Upvotes: 3

JARP
JARP

Reputation: 1249

In my case i was using a transaction inside the migration and Room could not update the hash using a Migration Helper

@get:Rule
val migrationTestHelper: MigrationTestHelper =

MigrationTestHelper(InstrumentationRegistry.getInstrumentation(),
                C2GDatabase::class.java.canonicalName,
                FrameworkSQLiteOpenHelperFactory()) 
/* Testing method throws error*/
db = migrationTestHelper.runMigrationsAndValidate(C2GDatabase.DB_NAME,
            3,
            false,
            C2GDatabase.Migration_1_2(),
            C2GDatabase.Migration_2_3())


override fun migrate(database: SupportSQLiteDatabase) {

/** 
    Error
    database.beginTransaction()
**/
database.execSQL("PRAGMA foreign_keys=off;")
database.execSQL("ALTER TABLE user RENAME TO user_old;")
database.execSQL("CREATE TABLE user ( id_user INTEGER PRIMARY KEY AUTOINCREMENT, external_id INTEGER NOT NULL;")
database.execSQL("INSERT INTO user ( id_user, external_id ) " +
                        " SELECT               id_user, external_id" +  
                        " FROM                 user_old;")

database.execSQL("CREATE UNIQUE INDEX idx_unique_user ON user (external_id);")
database.execSQL("PRAGMA foreign_keys=on;")
database.execSQL("DROP TABLE user_old;")
//database.endTransaction() 
}

Upvotes: 3

chaman
chaman

Reputation: 37

In My case ContentProvider and room database work together so first remove all callback of ContentProvider all over the application with database class which extends SqlLiteOpenHelper Class

Upvotes: 2

Bhargav Pandya
Bhargav Pandya

Reputation: 223

If you are upgrading Room version to 1.0.0-alpha9 from old version then please visit below article. Very Good Article for Migrate from old version to 1.0.0-alpha9 version.

https://medium.com/@manuelvicnt/android-room-upgrading-alpha-versions-needs-a-migration-with-kotlin-or-nonnull-7a2d140f05b9

In Room New Version 1.0.0-alpha9 Room adds support for the NOT NULL constraint.

That is going to change the schema that Room generates. Because it changes the schema, it also changes the identityHash of the DB and that is used by Room to uniquely identify every DB version. Therefore, we need a migration

Upvotes: 2

Ravi
Ravi

Reputation: 35589

Aniruddh Parihar 's answer gave me a hint and it solved.

Search for a class where you have extended RoomDatabase. There you will find version like below :

@Database(entities = {YourEntity.class}, version = 1)

just increase the version and problem is solved.

Upvotes: 30

Related Questions