Ver Fonte

Added a room database.

Thomas Chef há 3 anos atrás
pai
commit
244c103716

+ 25 - 0
.idea/jarRepositories.xml

@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="RemoteRepositoriesConfiguration">
+    <remote-repository>
+      <option name="id" value="central" />
+      <option name="name" value="Maven Central repository" />
+      <option name="url" value="https://repo1.maven.org/maven2" />
+    </remote-repository>
+    <remote-repository>
+      <option name="id" value="jboss.community" />
+      <option name="name" value="JBoss Community repository" />
+      <option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
+    </remote-repository>
+    <remote-repository>
+      <option name="id" value="MavenRepo" />
+      <option name="name" value="MavenRepo" />
+      <option name="url" value="https://repo.maven.apache.org/maven2/" />
+    </remote-repository>
+    <remote-repository>
+      <option name="id" value="Google" />
+      <option name="name" value="Google" />
+      <option name="url" value="https://dl.google.com/dl/android/maven2/" />
+    </remote-repository>
+  </component>
+</project>

+ 3 - 0
.idea/misc.xml

@@ -19,4 +19,7 @@
   <component name="ProjectType">
     <option name="id" value="Android" />
   </component>
+  <component name="SuppressKotlinCodeStyleNotification">
+    <option name="disableForAll" value="true" />
+  </component>
 </project>

+ 35 - 6
app/build.gradle

@@ -1,6 +1,8 @@
 plugins {
     id 'com.android.application'
     id 'org.jetbrains.kotlin.android'
+    id 'kotlin-android'
+    id 'kotlin-kapt'
 }
 
 android {
@@ -16,6 +18,14 @@ android {
         testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
     }
 
+    packagingOptions {
+        exclude 'META-INF/atomicfu.kotlin_module'
+    }
+
+    kotlinOptions {
+        jvmTarget = "1.8"
+    }
+
     buildTypes {
         release {
             minifyEnabled false
@@ -34,13 +44,32 @@ android {
     }
 }
 
+repositories {
+    mavenCentral()
+}
+
 dependencies {
+    implementation "androidx.appcompat:appcompat:$rootProject.appCompatVersion"
+    implementation "androidx.activity:activity-ktx:$rootProject.activityVersion"
+
+    // Room components
+    implementation "androidx.room:room-ktx:$rootProject.roomVersion"
+    kapt "androidx.room:room-compiler:$rootProject.roomVersion"
+    androidTestImplementation "androidx.room:room-testing:$rootProject.roomVersion"
+
+    // Lifecycle components
+    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$rootProject.lifecycleVersion"
+    implementation "androidx.lifecycle:lifecycle-livedata-ktx:$rootProject.lifecycleVersion"
+    implementation "androidx.lifecycle:lifecycle-common-java8:$rootProject.lifecycleVersion"
+
+    // Kotlin components
+    api "org.jetbrains.kotlinx:kotlinx-coroutines-core:$rootProject.coroutines"
+    api "org.jetbrains.kotlinx:kotlinx-coroutines-android:$rootProject.coroutines"
+
+    // UI
+    implementation "androidx.constraintlayout:constraintlayout:$rootProject.constraintLayoutVersion"
+    implementation "com.google.android.material:material:$rootProject.materialVersion"
 
-    implementation 'androidx.appcompat:appcompat:1.3.0'
-    implementation 'com.google.android.material:material:1.4.0'
-    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
+    // Location
     implementation 'com.google.android.gms:play-services-location:18.0.0'
-    testImplementation 'junit:junit:4.13.2'
-    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
-    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
 }

+ 1 - 0
app/src/main/AndroidManifest.xml

@@ -9,6 +9,7 @@
 
 
     <application
+        android:name=".JourneyGpsTrackerApplication"
         android:allowBackup="true"
         android:dataExtractionRules="@xml/data_extraction_rules"
         android:fullBackupContent="@xml/backup_rules"

+ 14 - 0
app/src/main/java/com/flacksta/chef/journeygpstracker/GpsData.kt

@@ -0,0 +1,14 @@
+package com.flacksta.chef.journeygpstracker
+
+import androidx.room.ColumnInfo
+import androidx.room.Entity
+import androidx.room.PrimaryKey
+
+@Entity(tableName = "pos_table")
+data class GpsData(
+        @PrimaryKey(autoGenerate = true) val id: Int,
+        @ColumnInfo(name = "ts") val ts: Long,
+        @ColumnInfo(name = "latitude") val latitude: Double,
+        @ColumnInfo(name = "longitude") val longitude: Double,
+        @ColumnInfo(name = "accuracy") val accuracy: Double,
+)

+ 20 - 0
app/src/main/java/com/flacksta/chef/journeygpstracker/GpsDataDao.kt

@@ -0,0 +1,20 @@
+package com.flacksta.chef.journeygpstracker
+
+import androidx.room.Dao
+import androidx.room.Insert
+import androidx.room.OnConflictStrategy
+import androidx.room.Query
+import kotlinx.coroutines.flow.Flow
+
+@Dao
+interface GpsDataDao {
+
+    @Query("SELECT * FROM pos_table ORDER BY ts ASC")
+    fun getGpsPositions(): Flow<List<GpsData>>
+
+    @Insert(onConflict = OnConflictStrategy.IGNORE)
+    suspend fun insert(gpsPos: GpsData)
+
+    @Query("DELETE FROM pos_table")
+    suspend fun deleteAll()
+}

+ 19 - 0
app/src/main/java/com/flacksta/chef/journeygpstracker/GpsPosRepository.kt

@@ -0,0 +1,19 @@
+package com.flacksta.chef.journeygpstracker
+
+import androidx.annotation.WorkerThread
+import kotlinx.coroutines.flow.Flow
+
+
+class GpsPosRepository(private val gpsDataDao: GpsDataDao) {
+
+    val allGpsData: Flow<List<GpsData>> = gpsDataDao.getGpsPositions()
+
+    // By default Room runs suspend queries off the main thread, therefore, we don't need to
+    // implement anything else to ensure we're not doing long running database work
+    // off the main thread.
+    @Suppress("RedundantSuspendModifier")
+    @WorkerThread
+    suspend fun insert(word: GpsData) {
+        gpsDataDao.insert(word)
+    }
+}

+ 69 - 0
app/src/main/java/com/flacksta/chef/journeygpstracker/GpsPosRoomDatabase.kt

@@ -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()
+
+        }
+    }
+}

+ 15 - 0
app/src/main/java/com/flacksta/chef/journeygpstracker/JourneyGpsTrackerApplication.kt

@@ -0,0 +1,15 @@
+package com.flacksta.chef.journeygpstracker
+
+import android.app.Application
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.SupervisorJob
+
+class JourneyGpsTrackerApplication : Application() {
+
+    // No need to cancel this scope as it'll be torn down with the process
+    val applicationScope = CoroutineScope(SupervisorJob())
+
+    val database by lazy { GpsPosRoomDatabase.getDatabase(this, applicationScope) }
+    val repository by lazy { GpsPosRepository(database.gpsDataDao()) }
+
+}

+ 3 - 0
app/src/main/java/com/flacksta/chef/journeygpstracker/MainScreenActivity.kt

@@ -23,6 +23,9 @@ class MainScreenActivity : AppCompatActivity() {
 
     private lateinit var mFusedLocationClient: FusedLocationProviderClient
 
+    //private val noteDatabase by lazy { GpsPosRoomDatabase.getDatabase(this) }
+
+
     override fun onCreate(savedInstanceState: Bundle?) {
         super.onCreate(savedInstanceState)
         binding = ActivityMainScreenBinding.inflate(layoutInflater)

+ 4 - 0
app/src/main/java/com/flacksta/chef/journeygpstracker/TrackingService.kt

@@ -24,6 +24,9 @@ class TrackingService : Service() {
     private lateinit var mLocationRequest: LocationRequest
     private lateinit var mLocationCallback: LocationCallback
 
+    //val database by lazy { GpsPosRoomDatabase.getDatabase(this) }
+    //val database by lazy { GpsPosRoomDatabase.getDatabase(this) }
+    //val repository by lazy { GpsPosRepository(database.gpsDataDao()) }
 
     override fun onCreate() {
         super.onCreate()
@@ -51,6 +54,7 @@ class TrackingService : Service() {
                     val acc = location.accuracy
                     Log.i(mTag, "Got location: $counter  $acc")
 
+
                 }
             }
         }

+ 29 - 4
build.gradle

@@ -1,10 +1,35 @@
 // Top-level build file where you can add configuration options common to all sub-projects/modules.
-plugins {
-    id 'com.android.application' version '7.2.1' apply false
-    id 'com.android.library' version '7.2.1' apply false
-    id 'org.jetbrains.kotlin.android' version '1.6.10' apply false
+buildscript {
+    ext.kotlin_version = '1.6.10'
+
+    repositories {
+        google()
+        mavenCentral()
+    }
+    dependencies {
+        classpath 'com.android.tools.build:gradle:7.1.0'
+        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
+    }
+}
+
+allprojects {
+    repositories {
+        google()
+        mavenCentral()
+    }
 }
 
 task clean(type: Delete) {
     delete rootProject.buildDir
+}
+
+ext {
+    activityVersion = '1.4.0'
+    appCompatVersion = '1.4.1'
+    constraintLayoutVersion = '2.1.3'
+    coreTestingVersion = '2.1.0'
+    coroutines = '1.6.0'
+    lifecycleVersion = '2.4.0'
+    materialVersion = '1.5.0'
+    roomVersion = '2.4.1'
 }

+ 0 - 15
settings.gradle

@@ -1,16 +1 @@
-pluginManagement {
-    repositories {
-        gradlePluginPortal()
-        google()
-        mavenCentral()
-    }
-}
-dependencyResolutionManagement {
-    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
-    repositories {
-        google()
-        mavenCentral()
-    }
-}
-rootProject.name = "JourneyGPSTracker"
 include ':app'