Skip to content

Instantly share code, notes, and snippets.

@nesk
Last active June 26, 2018 14:35
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/63f93e4f5e3fe2c924a759188391a4bb to your computer and use it in GitHub Desktop.
Save nesk/63f93e4f5e3fe2c924a759188391a4bb to your computer and use it in GitHub Desktop.
Android pre-populated database (full)
package com.example.example
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// This is an example, remember to use a background thread in production.
val myDatabase = MyDatabaseHelper(this).readableDatabase
myDatabase.rawQuery("SELECT * FROM my_awesome_table")
}
}
package com.example.example
import android.content.Context
import android.content.SharedPreferences
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import java.io.File
import java.io.FileOutputStream
class ActsDbHelper(val context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {
private val preferences: SharedPreferences = context.getSharedPreferences(
"${context.packageName}.database_versions",
Context.MODE_PRIVATE
)
private fun installedDatabaseIsOutdated(): Boolean {
return preferences.getInt(DATABASE_NAME, 0) < DATABASE_VERSION
}
private fun writeDatabaseVersionInPreferences() {
preferences.edit().apply {
putInt(DATABASE_NAME, DATABASE_VERSION)
apply()
}
}
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)
}
}
@Synchronized
private fun installOrUpdateIfNecessary() {
if (installedDatabaseIsOutdated()) {
context.deleteDatabase(DATABASE_NAME)
installDatabaseFromAssets()
writeDatabaseVersionInPreferences()
}
}
override fun getWritableDatabase(): SQLiteDatabase {
throw RuntimeException("The $DATABASE_NAME database is not writable.")
}
override fun getReadableDatabase(): SQLiteDatabase {
installOrUpdateIfNecessary()
return super.getReadableDatabase()
}
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"
const val DATABASE_NAME = "mydb"
const val DATABASE_VERSION = 1
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment