150

I am getting this error while running 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 we can do that in Room?

Ravi
  • 34,851
  • 21
  • 122
  • 183
  • 3
    If you don't care about the app's data, deleting all content from application settings might also help, since it just destroys the entire DB – O-9 Apr 24 '19 at 11:01

23 Answers23

206

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.

methodsignature
  • 4,152
  • 2
  • 20
  • 21
  • 6
    I wish they would include another fallback method for this case :( – BoD Sep 20 '17 at 09:22
  • 3
    In version `1.0.0-rc1` of Room the only thing that worked for me was to increment the database version. – Dick Lucas Oct 30 '17 at 23:54
  • 75
    I had android:allowBackup="true" in my AndroidManifest.xml which prevented the data from being cleared even after the app was uninstalled. I set this attribute to false and then reinstalled the app, which helped to get rid of the problem. Note that true is the default value for allowBackup, so if you don't use it at all, it might still cause the data to be retained. – Bartek Dec 21 '17 at 12:56
  • 1
    Such an explanation! I was uninstalling the app again and again because why upgrade the version in development? Oh boy, never thought that clearing data from settings is the key forward. Nice answer. Should be the accepted solution. – sud007 Feb 28 '19 at 12:50
  • 1
    Thank you for actually thinking about it before simply suggesting to increase the number. I knew that this couldn't be the right way when still developing the app. – Big_Chair May 15 '19 at 11:47
  • This approach won't work for existing users that would receive the new update in which the exception was introduced. Clearing the app cache only fixes your issue, but not everyone else's and as a user that's not intuitive. – 6rchid Mar 14 '23 at 16:50
  • Thanks @6rchid. I added some additional clarification based on your comment. – methodsignature Mar 21 '23 at 12:45
62

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.");
    }
}
live-love
  • 48,840
  • 22
  • 240
  • 204
  • The attribute android:allowBackup is deprecated from Android 12 and higher and may be removed in future versions. Consider adding the attribute android:dataExtractionRules specifying an @xml resource which configures cloud backups and device transfers on Android 12 and higher. – Mostafa Imani Jun 06 '22 at 07:55
  • I'm using an Android 12, targetSdk 33 and the trick with the AndroidManifest.xml, android:allowBackup="false", did it for me. It felt like if the database was still there because no matter how many times a cleared the data for the application every time I started the app again it will throw a that nasty "Room cannot verify the data integrity" exception – hmojica May 08 '23 at 06:00
38

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.

Vasily Kabunov
  • 6,511
  • 13
  • 49
  • 53
Hitesh Sahu
  • 41,955
  • 17
  • 205
  • 154
  • 2
    Will it not affect the users who will update the app from play store? – nimi0112 Mar 04 '19 at 04:00
  • 2
    I have followed the same way, but didn't work. Even I am trying to install on a fresh device from Android Studio, it shows same error :x – Sadat Apr 30 '19 at 13:41
  • @nimi0112 For your release variant, you should allow backup, however for your debug variant, you can turn it off – Chad Mx Dec 25 '19 at 14:37
28

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.

Ravi
  • 34,851
  • 21
  • 122
  • 183
23

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.

Aniruddh Parihar
  • 3,072
  • 3
  • 21
  • 39
  • 1
    Yes i got that error, that is why i have mentioned in question also that `It seems we need to update database version`. But i was not getting where that version was mentioned. Anyways thanks for that hint. – Ravi May 26 '17 at 09:08
  • You've reworded the error message but haven't provided any extra information to address the original poster's confusion. – Carl Rossman Nov 15 '20 at 16:25
  • @CarlRossman : You have to found your Database class in your project where you have used Database annotation, on that class you will find the Database version(Integer value), just increase it by one from current. – Aniruddh Parihar Nov 15 '20 at 19:12
18

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!

Marci
  • 899
  • 10
  • 13
  • Yes that worked. But strangely i was getting this issue on a device that erased completely and setup fresh just now. But simply clearing the data solved. – Ajith M A May 06 '20 at 19:40
  • 1
    This should not be done on production. You should not force all your users to clear data from the app. Better to write migration code by increasing version by 1 in your Room database. – Rajeev Jayaswal Jul 31 '20 at 19:30
  • Like @RajeevJayaswal has already mentioned, this is a terrible idea even for testing purposes. You should use the migration option instead. – Mbuodile Obiosio Apr 27 '21 at 01:45
  • Weird that uninstalling didn't work, but clearing app data did. – Anthony Cannon May 18 '23 at 13:44
10

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

peterzinho16
  • 919
  • 1
  • 15
  • 18
9

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

enter image description here

2nd Uninstall the app or Clear app data

Keshav Gera
  • 10,807
  • 1
  • 75
  • 53
8

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!

Divyanshu Negi
  • 592
  • 1
  • 5
  • 24
5

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.

Extremis II
  • 5,185
  • 2
  • 19
  • 29
3

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() 
}
JARP
  • 1,239
  • 12
  • 12
  • I struggle for several hours and this was the solution!! thank you!! – Javier Jun 14 '18 at 10:45
  • 1
    In the example above it's not the transaction that is a problem. You forgot to set transaction successful before ending it:
    
        database.beginTransaction()
        database.setTransactionSuccessful()
        database.endTransaction()
    
    – birukoff Jan 08 '19 at 12:33
3

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.

Harry .Naeem
  • 1,245
  • 3
  • 20
  • 33
2

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

Bhargav Pandya
  • 223
  • 1
  • 8
2

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

chaman
  • 37
  • 6
2
@Database(entities = {Tablename1.class, Tablename2.class}, version = 3, exportSchema = false)

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

Philipp
  • 335
  • 1
  • 6
  • 17
Rajeev Shetty
  • 1,534
  • 1
  • 17
  • 27
2

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");
    }
};
Hagar Magdy
  • 293
  • 2
  • 10
1

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
Daniel Jonker
  • 844
  • 10
  • 21
1

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() ...
    
Rahman Rezaee
  • 1,943
  • 16
  • 24
0

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.

Gavin Wright
  • 3,124
  • 3
  • 14
  • 35
0

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

Samir
  • 6,405
  • 5
  • 39
  • 42
0

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!

0

I know that wont be a proper way to do it but for easy solution you can go to the "device file explorer>data>data>(your package name)>databases" and delete all the files it will delete your files but it works if you want to just do it that way build and insert data it will get inserted and after you finalized your tables there wont be any need to delete further

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 04 '23 at 13:08
-2

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.

Ram Koti
  • 2,203
  • 7
  • 26
  • 36
Willey Hute
  • 939
  • 13
  • 18