Programming question & answer

How to copy database from assets folder in android using kotlin

RRTutors community answer Published Jan 7, 2020

Answer

We can copy database from assets folde by

class CopyAssetDatabaseOpenHelper(private val context: Context) {

companion object {

    private val DB_NAME = "dbName.db"
}

fun openDatabase(): SQLiteDatabase {
    val dbFile = context.getDatabasePath(DB_NAME)


    if (!dbFile.exists()) {
        try {
           val checkDB = context.openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE,null)

            checkDB?.close()
            copyDatabase(dbFile)
        } catch (e: IOException) {
            throw RuntimeException("Error creating source database", e)
        }

    }
    return SQLiteDatabase.openDatabase(dbFile.path, null, SQLiteDatabase.OPEN_READWRITE)
}


private fun copyDatabase(context:Context) {
            val dbFile = context.getDatabasePath("logicaldb")
            val assetdb = context.assets.open("logicaldb")
            val currentDB = FileOutputStream(dbFile)

            val buffer = ByteArray(1024)
            while (assetdb.read(buffer) > 0) {
                currentDB.write(buffer)
                Log.d("#DB", "Copying "+buffer.toString())
            }

            currentDB.flush()
            currentDB.close()
            assetdb.close()

        }
    }