Room cannot verify the data integrity

84,970

Solution 1

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.

Solution 2

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 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. Forgetting to remove this call and then forgetting to upgrade the database will result in data loss.

// 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.

Solution 3

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.");
    }
}

Solution 4

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.

Solution 5

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.

Share:
84,970
Ravi
Author by

Ravi

Follow me on instagram for more programming posts: https://www.instagram.com/ravi.rupareliya/

Updated on June 03, 2021

Comments

  • Ravi
    Ravi about 3 years

    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
    Ravi about 7 years
    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.
  • BoD
    BoD almost 7 years
    I wish they would include another fallback method for this case :(
  • Dick Lucas
    Dick Lucas over 6 years
    In version 1.0.0-rc1 of Room the only thing that worked for me was to increment the database version.
  • Bartek
    Bartek over 6 years
    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.
  • guness
    guness over 6 years
    @Bartek this comment now deserves to be an answer.
  • Javier
    Javier about 6 years
    I struggle for several hours and this was the solution!! thank you!!
  • Roman Soviak
    Roman Soviak over 5 years
    After that is still crash
  • Extremis II
    Extremis II over 5 years
    what is the exception? please put up the log to narrow down issue.
  • Roman Soviak
    Roman Soviak over 5 years
    Thanks, everything is OK now. I read about android:allowBackup="true" and use it wisely
  • Ridcully
    Ridcully over 5 years
    @user7856586 So what about allowBackup? Could you please enlighten us with your wisdom?
  • Roman Soviak
    Roman Soviak over 5 years
    @Ridcully you can read about that here Why you are so angry?
  • birukoff
    birukoff over 5 years
    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>
  • Dan
    Dan over 5 years
    Thank you! Going to Settings > Apps > [App Name] > Storage > Clear Storage worked for me!
  • sud007
    sud007 over 5 years
    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.
  • nimi0112
    nimi0112 over 5 years
    Will it not affect the users who will update the app from play store?
  • Sadat
    Sadat about 5 years
    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
  • Big_Chair
    Big_Chair about 5 years
    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.
  • A.Alqadomi
    A.Alqadomi over 4 years
    This answer is pure gold . the clear data worked perfectly for me , I was uninstalling and installing again and still receive the error .Also the additional information is awesome .
  • Chad Mx
    Chad Mx over 4 years
    @nimi0112 For your release variant, you should allow backup, however for your debug variant, you can turn it off
  • Bipin Bharti
    Bipin Bharti over 4 years
    Yes this is proper Way
  • Ajith M A
    Ajith M A about 4 years
    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.
  • GreenROBO
    GreenROBO about 4 years
    Can you help me with the same? I am unable to find version in DB Browser for SQLite
  • Gavin Wright
    Gavin Wright about 4 years
    It's under the "Edit pragmas" tab. It's called "User Version".
  • GreenROBO
    GreenROBO about 4 years
    Yes. I got it. Thanks for the help Gavin :)
  • Rajeev Jayaswal
    Rajeev Jayaswal almost 4 years
    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.
  • Carl Rossman
    Carl Rossman over 3 years
    You've reworded the error message but haven't provided any extra information to address the original poster's confusion.
  • Aniruddh Parihar
    Aniruddh Parihar over 3 years
    @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.
  • Mehdi Fracso
    Mehdi Fracso over 3 years
    Uninstalling the app worked for me, thanks!
  • Mbuodile Obiosio
    Mbuodile Obiosio about 3 years
    Like @RajeevJayaswal has already mentioned, this is a terrible idea even for testing purposes. You should use the migration option instead.
  • Mostafa Imani
    Mostafa Imani about 2 years
    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.