# Copying database from assets creates a empty database

**URL:** <https://discuss.kotlinlang.org/t/copying-database-from-assets-creates-a-empty-database/6914>\
**Category:** Android\
**Created:** [March 6, 2018, 7:43pm UTC](https://discuss.kotlinlang.org/t/copying-database-from-assets-creates-a-empty-database/6914 "2018-03-06T19:43:40Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![allnex](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/allnex/32/4861_2.png) [@allnex](https://discuss.kotlinlang.org/u/allnex)\
**Post date:** [March 6, 2018, 7:43pm UTC](https://discuss.kotlinlang.org/t/copying-database-from-assets-creates-a-empty-database/6914/1 "2018-03-06T19:43:40Z")

</div>

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](https://github.com/Kotlin/anko/wiki/Anko-SQLite) to query the database works perfectly, but with the code above, querying any table throws `no such table` error.

Thanks.
