代码之家  ›  专栏  ›  技术社区  ›  fermoga

我不能在我的房间数据库中执行一到两次以上的插入,因为在这些插入之后,它根本不会保存数据

  •  0
  • fermoga  · 技术社区  · 7 年前

    无论是表X中的插入操作还是表Y中的删除操作,问题是只有一个操作正在执行,为了使其再次工作,我需要重新运行我的应用程序,进行新的APK安装。也就是说,如果我在表X中插入,并尝试在表Y中进行另一次插入,尽管它会在应用程序中列出,但它不会持久存在于数据库中。

    我通过在调试模式下运行应用程序并使用 com.amitshekhar.android:debug-db:1.0.4 .这很奇怪,从数据库中列出而不在数据库中。然后,当再次运行应用程序时,这些“幽灵数据”就会消失。

    除了操作代码,我不知道该显示什么。最简单的一个,a Student 插入:

    fun onClickSaveStudentButton(view: View?) {
        val studentName: String = mEdtStudentName?.text.toString()
        val studentEntry = Student(null, studentName)
    
        thread { mDb?.studentsDao()?.insert(studentEntry) }
    
        finish()
    }
    

    名称只有一个字段,执行插入的线程。它有时会允许我插入两次,但在插入之后,同样的问题也会发生。我想可能是因为 thread ,所以我安装了 Anko 利用 doAsync ,但问题仍然存在。

    这是要插入的DAO函数:

    @Insert
    fun insert(data: Student)
    

    这里出了什么问题?为什么它只允许我插入一两次?

    数据库类:

    @Database(entities = [(Schedule::class), (Student::class)], version = 1)
    abstract class AppDatabase : RoomDatabase() {
        companion object {
            @Volatile
            private var sInstance: AppDatabase? = null
    
            fun getInstance(context: Context): AppDatabase = sInstance ?: synchronized(this) {
                sInstance ?: Room.databaseBuilder(
                    context,
                    AppDatabase::class.java,
                    Constants.DATABASE_NAME
                ).build().also {
                    sInstance = it
                }
            }
        }
    
        abstract fun scheduleDao(): ScheduleDao
        abstract fun studentsDao(): StudentDao
    }
    

    举个例子, 大学生 型号:

    @Entity(tableName = "students")
    class Student constructor(
        @PrimaryKey(autoGenerate = true) var id: Int?,
        @ColumnInfo(name = "name") var name: String?
    )
    

    完整代码 here .

    0 回复  |  直到 7 年前