How to check if a DB exists in Android?

后端 未结 4 554
广开言路
广开言路 2021-01-19 15:05

I am using Room API to implement a DB in my Android app. It seems that every time I load my app it tries to create the database again and again. Is there any way to restrict

4条回答
  •  滥情空心
    2021-01-19 15:35

    You can get count of entities in db (TODO app - example). entities > 0.

    class App: Application() {
        override fun onCreate() {
            super.onCreate()
            instance = this
            database = Room.databaseBuilder(applicationContext,
                AppDatabase::class.java, "database").build()
        }
        companion object {
            lateinit var instance: App
            lateinit var database: AppDatabase
        }
    }
    

    //DB class

     @Database(entities = [Task::class], version = 1, exportSchema = false)
           abstract class AppDatabase : RoomDatabase() {
           abstract fun taskDao(): TaskDao
    }
    

    //Dao interface

       @Dao
        interface TaskDao {
            @Query("SELECT COUNT(id) FROM tasks")
            fun getTasksCount(): Int
        }
    

    //Model

    @Entity(indices = [Index(value = ["title"], unique = true)], tableName ="tasks")
        class Task(
            var title: String = "",
            var description: String = "",
            var date: Date,
            @Embedded 
            var remind: Constants.RemindPeriod = Constants.RemindPeriod.MIN5,
            @Embedded
            var prior: Priority) : Serializable {
            @PrimaryKey(autoGenerate = true)
            var id: Long = 0}
    

    //CheckDB

     private fun checkDatabaseState() {
            doAsync {
                val db = App.database
                val entityCount = db.taskDao().getTasksCount().or(0)
                isDatabaseNotEmpty = entityCount > 0
            }
        }  
    

提交回复
热议问题