How to copy database from assets folder in android using kotlin

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()

        }
    }

 


Subscribe For Daily Updates

Flutter Questions
Android Questions