Copying database from assets creates a empty database


#1

I’m having problems copying an already existing database from the assets folder to the databases folder. The original database is 5.9MB, but with the code below, it creates a 12KB database with the android_metadata table, which is already on my database.

Here is the code:

class Database(private val ctx: Context = App.instance) : ManagedSQLiteOpenHelper(ctx, DB_NAME, null, DB_VERSION), AnkoLogger {
    companion object {
        val instance by lazy { Database() }
        private const val DB_NAME = "dex.db"
        private const val DB_VERSION = 1
    }

    override fun onCreate(db: SQLiteDatabase) {
        if (!ctx.getDatabasePath(DB_NAME).exists()) {
            info("Creating database ${db.path}.")
            copyDatabase()
        }
    }

    override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
        if (newVersion > oldVersion) {
            info("Updating database ${db.path} from version $oldVersion to version $newVersion.")
            copyDatabase()
        }
    }

    private fun copyDatabase() {
        info("Copying database to data folder.")
        ctx.assets.open(DB_NAME).buffered().use { input ->
            FileOutputStream(ctx.getDatabasePath(DB_NAME)).use { out ->
                input.copyTo(out)
            }
        }
    }
}

Copying the database manually with Device File Explorer from Android Studio and using Anko SQLite to query the database works perfectly, but with the code above, querying any table throws no such table error.

Thanks.