|
@@ -0,0 +1,69 @@
|
|
|
|
+package com.flacksta.chef.journeygpstracker
|
|
|
|
+
|
|
|
|
+import android.content.Context
|
|
|
|
+import androidx.room.Database
|
|
|
|
+import androidx.room.Room
|
|
|
|
+import androidx.room.RoomDatabase
|
|
|
|
+import androidx.sqlite.db.SupportSQLiteDatabase
|
|
|
|
+import kotlinx.coroutines.CoroutineScope
|
|
|
|
+import kotlinx.coroutines.Dispatchers
|
|
|
|
+import kotlinx.coroutines.launch
|
|
|
|
+
|
|
|
|
+@Database(entities = [GpsData::class], version = 1, exportSchema = false)
|
|
|
|
+public abstract class GpsPosRoomDatabase : RoomDatabase() {
|
|
|
|
+
|
|
|
|
+ abstract fun gpsDataDao(): GpsDataDao
|
|
|
|
+
|
|
|
|
+ companion object {
|
|
|
|
+ @Volatile
|
|
|
|
+ private var INSTANCE: GpsPosRoomDatabase? = null
|
|
|
|
+
|
|
|
|
+ fun getDatabase(
|
|
|
|
+ context: Context,
|
|
|
|
+ scope: CoroutineScope
|
|
|
|
+ ): GpsPosRoomDatabase {
|
|
|
|
+ // if the INSTANCE is not null, then return it,
|
|
|
|
+ // if it is, then create the database
|
|
|
|
+ return INSTANCE ?: synchronized(this) {
|
|
|
|
+ val instance = Room.databaseBuilder(
|
|
|
|
+ context.applicationContext,
|
|
|
|
+ GpsPosRoomDatabase::class.java,
|
|
|
|
+ "gpspos_database"
|
|
|
|
+ )
|
|
|
|
+ // Wipes and rebuilds instead of migrating if no Migration object.
|
|
|
|
+ // Migration is not part of this codelab.
|
|
|
|
+ .fallbackToDestructiveMigration()
|
|
|
|
+ .addCallback(GpsPosRoomDatabaseCallback(scope))
|
|
|
|
+ .build()
|
|
|
|
+ INSTANCE = instance
|
|
|
|
+ // return instance
|
|
|
|
+ instance
|
|
|
|
+ }
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ private class GpsPosRoomDatabaseCallback(
|
|
|
|
+ private val scope: CoroutineScope
|
|
|
|
+ ) : RoomDatabase.Callback() {
|
|
|
|
+ /**
|
|
|
|
+ * Override the onCreate method to populate the database.
|
|
|
|
+ */
|
|
|
|
+ override fun onCreate(db: SupportSQLiteDatabase) {
|
|
|
|
+ super.onCreate(db)
|
|
|
|
+ // If you want to keep the data through app restarts,
|
|
|
|
+ // comment out the following line.
|
|
|
|
+ INSTANCE?.let { database ->
|
|
|
|
+ scope.launch(Dispatchers.IO) {
|
|
|
|
+ populateDatabase(database.gpsDataDao())
|
|
|
|
+ }
|
|
|
|
+ }
|
|
|
|
+ }
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ suspend fun populateDatabase(gpsDataDao: GpsDataDao) {
|
|
|
|
+ // Start the app with a clean database every time.
|
|
|
|
+ // Not needed if you only populate on creation.
|
|
|
|
+ gpsDataDao.deleteAll()
|
|
|
|
+
|
|
|
|
+ }
|
|
|
|
+ }
|
|
|
|
+}
|