3

I searched all the internet to find a way that allows me to copy a database from assets folder using kotlin but there is none so please does anyone knows how to do it in kotlin?? Because I'm working on project and everything is stopped on this step Thanks in advance

marcel_maro
  • 85
  • 2
  • 9
  • I want it using kotlin and i tried to convert the java code to kotlin but it didn't work and that's why i want it to be in kotlin, Thank you for the help Anyway – marcel_maro Jan 29 '18 at 05:08

1 Answers1

4

Add this class for copy a database from assets in Kotlin:

class AssetDatabaseOpenHelper(private val context: Context) {

companion object {

    private val DB_NAME = "asset_db_name.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)
}

@SuppressLint("WrongConstant")
private fun copyDatabase(dbFile: File) {
    val `is` = context.assets.open(DB_NAME)
    val os = FileOutputStream(dbFile)

    val buffer = ByteArray(1024)
    while (`is`.read(buffer) > 0) {
        os.write(buffer)
        Log.d("#DB", "writing>>")
    }

    os.flush()
    os.close()
    `is`.close()
    Log.d("#DB", "completed..")
}

}

And than open or create database from your activity using

val adb = AssetDatabaseOpenHelper(this)

adb.openDatabase()

Log.d("#DB","writing>>"); will show you database entries in Logcat.