sqlite – Room cannot verify the data integrity in Android-ThrowExceptions

Exception or error:

MainActivity class

public class MainActivity extends BaseActivity {

    private AppDatabase db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Database creation
        db = Room.databaseBuilder(getApplicationContext(),
                AppDatabase.class, "Medimap-db").build();
//        Profile profile=new Profile("rajitha","12-2-345","male","no 345","test med","test emergency","testurl");
//        db.profileDao().insert(profile);
//        Toast.makeText(getApplicationContext(),"success",Toast.LENGTH_SHORT).show();
        new DatabaseAsync().execute();


    }

    private class DatabaseAsync extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            //Perform pre-adding operation here.
        }

        @Override
        protected Void doInBackground(Void... voids) {
            //Let's add some dummy data to the database.
            Profile profile = new Profile("rajitha", "12-2-345", "male", "no 345", "test med", "test emergency", "testurl");
            db.profileDao().insert(profile);


            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            Toast.makeText(getApplicationContext(), "success", Toast.LENGTH_SHORT).show();
            //To after addition operation here.
        }
    }

}

AppDatabase class

   @Database(entities = {Profile.class, Medicine.class}, version = 1)
    public abstract class AppDatabase extends RoomDatabase {
        public abstract ProfileDao profileDao();
        public abstract MedicineDao medicineDaoDao();
    }

ProfileDao

@Dao
public interface ProfileDao {

    @Query("SELECT * FROM profile")
    List<Profile> getAll();

//    @Query("SELECT * FROM user WHERE uid IN (:userIds)")
//    List<Profile> loadAllByIds(int[] userIds);

//    @Query("SELECT * FROM user WHERE first_name LIKE :first AND "
//            + "last_name LIKE :last LIMIT 1")
//    User findByName(String first, String last);

    @Insert
    void insertAll(Profile... profiles);

    @Insert
    void insert(Profile profile);

    @Delete
    void delete(Profile profile);
}

Here I got an error after the first run of the app. It seems like the app is trying to create DATABASE once again, but there already is an existing one so they suggested to change the version code. My requirement is that I only need to insert a new data set. How can I achieve that? Thanks in advance. Here is the logcat error:

Caused by: java.lang.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.
How to solve:

If you’re only developing the application at the moment, it means that you are not on Production and uninstalling the app from device and install it again will work as required.

###

Android 6.0+

For those of you who come across this now a days, simply uninstalling might not help and it will drive you nuts, so before you have to figure it out, let me share the issue: Google introduced the “autobackup” functionality in
Android 6.0, which brings back a DB when you reinstall. (https://developer.android.com/guide/topics/data/autobackup.html)

You can simply add…

<application ...
    android:allowBackup="false">
</app>

…to disable this functionality and you are good to go (now you can simply uninstall to delete the database).

###

If you don’t care about migrations when update entities:

  1. Increase database version
  2. Add fallbackToDestructiveMigration() method at the time of building database, e.g:

    Room.databaseBuilder(appContext, AppDatabase.class, “appdb.db”)
    .fallbackToDestructiveMigration()
    .build();

Hope this help someone 😉

###

Increase the version:

@Database(entities = {EmployeeEntry.class}, version = 2, exportSchema = false)

Took from
link

###

There are 3 ways to fix this data integrity exception.

1) If you don’t want to increase your Database version and you can bear data loss
Just clear your App data from App settings after installing new build in device and launch App again, it would work without data integrity exception

2) If you can increase your Database version but still you can bear data loss
If you want to make it seamless( no crash due to schema update), you can simply increase Database version (let say from 1 to 2) and mention Default migration strategy in Database Builder fallbackToDestructiveMigration(). Then on installing this App, your previous DB data would clear up and you wouldn’t get this data integrity exception.

3) If you can increase your Database version and also want to save your previous data
You need to increase your Database version(let say from 1 to 2) but also need to implement proper migrations logic (based on your lower version and higher version) in your App. Then on installing new version, you will not get this data integrity exception.
For migrations of Room you can read out this nice article written for migrations

For official documentation of Room migrations go to link

###

In my case, reinstalling didn’t help and also I couldn’t set android:allowBackup:true because one of the libraries I had used required it. So I went to Settings > Apps > My app, and cleared data and memory for that app. Problem gone;)

###

Step 1: Install new build

Step 2: Clear all app data from Settings.

Step 3: Open app ( will work fine now )

###

You can also use adb shell pm uninstall com.package.app in your terminal to fully uninstall the app. After that, install it again and the error will disappear.

Leave a Reply

Your email address will not be published. Required fields are marked *