我搜索了所有互联网,找到了一种方法,允许我使用kotlin从assets文件夹复制数据库,但没有,所以请有人知道如何在kotlin中做到这一点?因为我正在研究项目,所有事情都在此步骤中停止 提前致谢
答案 0 :(得分:1)
添加此类以从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..")
}
}
而不是使用
打开或创建活动数据库val adb = AssetDatabaseOpenHelper(this)
adb.openDatabase()
Log.d("#DB""&写入GT;>&#34);将在Logcat中显示数据库条目。