Search code examples
databaseimportandroid-room

Can Android Room validate an imported database before it is opened?


Problem: I can't seem to get an imported database to fail in Android Room until first queried? I'm wanting to try/catch and validate a database and I'm not succeeding on catching it before the first query. I always thought Android Room validated the database at the moment of instance creation and build against the schema, but apparently not. So the database fails upon first query.

What I'm trying to do: This app manages multiple databases that can be shared between users. So databases can be imported or exported. I suspect that at some point, someone will attempt to import the wrong database and or structure or do something to cause it to fail. I'm trying to catch the failure at the instance / build of the database or sooner.

What I've tried: I have a try/catch/finally block at the first instance creation, but it is only failing when first queried... then it notices that a table or column is missing. I'd like to catch it sooner if possible. I've looked at the RoomDatabase methods but nothing specifically applies to validation that I see other than just letting it break.


Solution

  • I always thought Android Room validated the database at the moment of instance creation and build against the schema, but apparently not.

    The database validation is part of the open process, which does not happen until you actually try to access the database, as opposed to when getting the instance.

    I can't seem to get an imported database to fail in Android Room until first queried?

    When you get the instance you can force an open by getting (or trying to get) a SupportSQLiteDatabase by using either getWritableDatabase or getReadableDatabase via the instance's openHelper.

    e.g.

    (Kotlin)

        db = TheDatabase.getInstance(this)
        try {
            val supportDB = db.openHelper.writableDatabase
        }
        catch(e: Exception) {
            ....
        }
    

    (Java)

        db = TheDatabase.getInstance(this);
        try {
            SupportSQLiteDatabase supportDB = db.getOpenHelper().getWritableDatabase();
        }
        catch (Exception e) {
            ....
        }