Skip to content

Instantly share code, notes, and snippets.

@nesk
Last active June 26, 2018 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nesk/acd4de381d74a69a553ecd2c792e6a2c to your computer and use it in GitHub Desktop.
Save nesk/acd4de381d74a69a553ecd2c792e6a2c to your computer and use it in GitHub Desktop.
Android pre-populated database (installation method)
package com.example.example
// ...
import java.io.File
import java.io.FileOutputStream
class ActsDbHelper(val context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {
private fun installDatabaseFromAssets() {
val inputStream = context.assets.open("$ASSETS_PATH/$DATABASE_NAME.sqlite3")
try {
val outputFile = File(context.getDatabasePath(DATABASE_NAME).path)
val outputStream = FileOutputStream(outputFile)
inputStream.copyTo(outputStream)
inputStream.close()
outputStream.flush()
outputStream.close()
} catch (exception: Throwable) {
throw RuntimeException("The $DATABASE_NAME database couldn't be installed.", exception)
}
}
override fun onCreate(db: SQLiteDatabase?) {
// Nothing to do
}
override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
// Nothing to do
}
companion object {
const val ASSETS_PATH = "databases"
// ...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment