我无法联系到数据库检查员来添加数据

I can't reach database inspector to add data

我的应用程序构建成功,但我无法连接到数据库检查员。每当我打开数据库检查器时,它都不显示任何数据库。我尝试重新启动,但没有用。我在从 google 课程下载的另一个应用程序中尝试了 inspector,它在那里工作。我被困在这里,我该如何克服这个问题。

这就是我打开数据库检查器时看到的内容:

实体

@Entity
data class Note(
    @PrimaryKey(autoGenerate = true)
    val id: Long = 0,
    @ColumnInfo(name = "note_text")
    val noteText: String,
    @ColumnInfo(name = "note_date")
    val noteDate: Date
)

@Dao
interface NoteDao {

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insert(note: Note)

    @Update
    suspend fun update(note: Note)

    @Delete
    suspend fun delete(note: Note)

    @Query("SELECT * FROM Note WHERE id = :id")
    fun getNote(id: Long): Flow<Note>

    @Query("SELECT * from Note ORDER BY note_date DESC")
    fun getAllNotes(): Flow<List<Note>>
}

房间数据库

private const val TAG = "NoteRoomDatabase"

@Database(entities = [Note::class], version = 1, exportSchema = false)
@TypeConverters(Converters::class)
abstract class NoteRoomDatabase: RoomDatabase() {

    abstract fun noteDao(): NoteDao

    companion object {
        @Volatile
        private var INSTANCE: NoteRoomDatabase? = null

        fun getDatabase(context: Context): NoteRoomDatabase {
            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    NoteRoomDatabase::class.java,
                    "note_database")
                    .fallbackToDestructiveMigration()
                    .build()

                Log.d(TAG, "Database created!")
                INSTANCE = instance
                return instance
            }
        }

    }
}

申请

class NotesApplication : Application() {

    val database: NoteRoomDatabase by lazy { NoteRoomDatabase.getDatabase(this) }
}

视图模型工厂

class AppViewModelFactory(private val noteDao: NoteDao) : ViewModelProvider.Factory {
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(AppViewModel::class.java)) {
            @Suppress("UNCHECKED_CAST")
            return AppViewModel(noteDao) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }
}

我如何从片段中调用它

private val viewModel: AppViewModel by activityViewModels {
    AppViewModelFactory(
        (activity?.application as NotesApplication).database.noteDao()
    )
}

为此你必须先创建你的数据库 .. 当你 运行 你的 activity 这不会执行你的数据库 类,所以在你的第一个主要 activity

 lifecycleScope.launch(Dispatchers.IO){
                 val database: NoteRoomDatabase by lazy { NoteRoomDatabase.getDatabase(this)
             
               
            }

您什么也看不到的原因是在尝试访问数据库之前什么都没有。

您可以通过获取 SupportSQLiteDatabase 强制打开数据库(即使您不使用它)

例如

val database: NoteRoomDatabase by lazy { NoteRoomDatabase.getDatabase(this) }
database.openHelper.writableDatabase //<<<<<<<<<< ADDED

您也可以在构建后强制在 getDatabase 函数中打开,例如

instance.openHelper.writableDatabase