Room cannot verify the data integrity
Asked Answered
C

24

152

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?

Coalition answered 26/5, 2017 at 8:46 Comment(1)
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 DBAsti
C
29

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.

Coalition answered 26/5, 2017 at 9:7 Comment(0)
B
213

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.

Bolzano answered 30/8, 2017 at 18:59 Comment(7)
I wish they would include another fallback method for this case :(Grassquit
In version 1.0.0-rc1 of Room the only thing that worked for me was to increment the database version.Lackey
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.Forbade
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.Karlynkarma
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.Mychael
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.Durston
Thanks @6rchid. I added some additional clarification based on your comment.Bolzano
E
65

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.");
    }
}
Ebonee answered 17/11, 2018 at 16:41 Comment(2)
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.Treadle
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" exceptionDumdum
R
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.

Roo answered 17/1, 2018 at 2:58 Comment(3)
Will it not affect the users who will update the app from play store?Midian
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 :xMerrymaking
@Midian For your release variant, you should allow backup, however for your debug variant, you can turn it offBrockington
C
29

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.

Coalition answered 26/5, 2017 at 9:7 Comment(0)
M
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.

Mares answered 26/5, 2017 at 8:51 Comment(3)
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.Coalition
You've reworded the error message but haven't provided any extra information to address the original poster's confusion.Ehrenberg
@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.Mares
A
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!

Aweigh answered 14/8, 2019 at 11:44 Comment(4)
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.Cabotage
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.Meathead
Like @RajeevJayaswal has already mentioned, this is a terrible idea even for testing purposes. You should use the migration option instead.Letdown
Weird that uninstalling didn't work, but clearing app data did.Tetrastichous
I
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

Incorporating answered 9/4, 2020 at 23:19 Comment(0)
D
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

Duggan answered 3/9, 2019 at 9:32 Comment(0)
D
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!

Duplex answered 24/3, 2019 at 19:28 Comment(0)
B
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.

Bootless answered 19/8, 2018 at 18:36 Comment(6)
After that is still crashSayre
what is the exception? please put up the log to narrow down issue.Bootless
Thanks, everything is OK now. I read about android:allowBackup="true" and use it wiselySayre
@user7856586 So what about allowBackup? Could you please enlighten us with your wisdom?Gracye
@Gracye you can read about that here Why you are so angry?Sayre
Thank you! Going to Settings > Apps > [App Name] > Storage > Clear Storage worked for me!Ney
H
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() 
}
Highlight answered 18/4, 2018 at 22:38 Comment(2)
I struggle for several hours and this was the solution!! thank you!!Earthen
In the example above it's not the transaction that is a problem. You forgot to set transaction successful before ending it: <pre><code> database.beginTransaction() database.setTransactionSuccessful() database.endTransaction() </code></pre>Gomuti
O
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.

Out answered 21/7, 2018 at 8:59 Comment(0)
A
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

Abc answered 31/8, 2017 at 13:43 Comment(0)
B
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

Bistro answered 6/4, 2018 at 9:22 Comment(0)
R
2
@Database(entities = {Tablename1.class, Tablename2.class}, version = 3, exportSchema = false)

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

Ritchie answered 6/11, 2019 at 9:15 Comment(0)
Q
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");
    }
};
Queeniequeenly answered 24/11, 2019 at 11:11 Comment(1)
Yes this is proper WayRillings
A
2

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.

Apathetic answered 4/5, 2023 at 10:12 Comment(0)
P
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
Poly answered 29/7, 2019 at 15:9 Comment(0)
L
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() ...
    
Lalita answered 24/2, 2023 at 15:59 Comment(0)
S
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.

Sammons answered 25/3, 2020 at 1:47 Comment(3)
Can you help me with the same? I am unable to find version in DB Browser for SQLiteHarijan
It's under the "Edit pragmas" tab. It's called "User Version".Sammons
Yes. I got it. Thanks for the help Gavin :)Harijan
A
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

Abnegate answered 7/4, 2021 at 8:37 Comment(0)
F
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!

Foxe answered 19/3, 2023 at 15:4 Comment(0)
R
0

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

After that, uninstall and reinstall your application.

Remark answered 1/4 at 7:34 Comment(1)
This answer doesn't seem better than any of the other 23 in this thread. Especially considering the question has already been answered by OP with an issue in his code.Mcconaghy
B
-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.

Basilisk answered 12/12, 2019 at 5:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.