我想通过房间从数据库中选择数据。

这是我的代码。

数据库

@Database(entities = [TicketDb::class], version = 1)
@TypeConverters(DatabaseConverters::class)
abstract class MyDatabase : RoomDatabase() {

    abstract fun ticketDbDao(): TicketDbDao

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

        fun getDatabase(context: Context, scope: CoroutineScope): MyDatabase {
            val tempInstance = INSTANCE
            if (tempInstance != null) {
                return tempInstance
            }
            synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    MyDatabase::class.java,
                    "my_database"
                )
        .build()
                INSTANCE = instance
                return instance
            }
        }
    }
}

数据类
@Entity(tableName = "ticket_table")
data class TicketDb (@ColumnInfo(name = "ticketnumber")  var ticketnumber: String = "1234567") {
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "id") var id: Int = 0
}


@Dao
interface TicketDbDao {

    @Insert
    suspend fun insert(ticket: TicketDb)

    @Query("SELECT * FROM ticket_table ORDER BY id DESC")
    fun getAllTickets(): LiveData<List<TicketDb>>
}

存储库
class TicketRepository (private val ticketDbDao: TicketDbDao) {

    val allTickets: LiveData<List<TicketDb>> = ticketDbDao.getAllTickets()

    @WorkerThread
    suspend fun insert(ticket: TicketDb) {
        ticketDbDao.insert(ticket)
    }

}

View 模型
var ticketRepository: TicketRepository

val allTickets: LiveData<List<TicketDb>>

init {
    val ticketDao = MeinLottoDatabase.getDatabase(application, viewModelScope).ticketDbDao()
    ticketRepository = TicketRepository(ticketDao)
    allTickets = ticketRepository.allTickets
}

fun saveTicket() = viewModelScope.launch(Dispatchers.IO) {
        ticketRepository.insert(ticket.value!!.toTicketDb())
}

saveTicket方法有效。我已经下载了数据库,并且所有保存的条目都存在。
但是每当我调用ticketRepository.allTickets时,我都会得到一个空列表。

我已经在Callable对象的调用方法中的自动生成的TicketDbDao_Impl类中设置了一个断点,但是从未达到断点。
@Override
  public LiveData<List<TicketDb>> getAllTickets() {
    final String _sql = "SELECT * FROM ticket_table";
    final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 0);
    return __db.getInvalidationTracker().createLiveData(new String[]{"ticket_table"}, false, new Callable<List<TicketDb>>() {
      @Override
      public List<TicketDb> call() throws Exception {
        final Cursor _cursor = DBUtil.query(__db, _statement, false);
        try {
          // BREAKPOINT here
          final int _cursorIndexOfId = CursorUtil.getColumnIndexOrThrow(_cursor, "id");
          final int _cursorIndexOfName = CursorUtil.getColumnIndexOrThrow(_cursor, "name");

最佳答案

我尝试了相同的代码,做了很少的更改,但对我来说工作正常

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val ticket1 = TicketDb("1")
        val ticket2 = TicketDb("12")
        val ticket3 = TicketDb("1123")
        val ticket4 = TicketDb("4214")

        MyDatabase.getDatabase(applicationContext).ticketDbDao()?.run {
            insert(ticket1)
            insert(ticket2)
            insert(ticket3)
            insert(ticket4)
        }

        val data = MyDatabase.getDatabase(applicationContext).ticketDbDao().getAllTickets()

        Log.i("Hardik", "Data :$data")

    }
}

我的数据库
@Database(entities = [TicketDb::class], version = 1)
abstract class MyDatabase : RoomDatabase() {

    abstract fun ticketDbDao(): TicketDbDao

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

        fun getDatabase(context: Context): MyDatabase {
            val tempInstance = INSTANCE
            if (tempInstance != null) {
                return tempInstance
            }
            synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    MyDatabase::class.java,
                    "my_database"
                ).allowMainThreadQueries().build()
                INSTANCE = instance
                return instance
            }
        }
    }
}

TicketDb
@Entity(tableName = "ticket_table")
data class TicketDb(@ColumnInfo(name = "ticketnumber") var ticketnumber: String = "1234567") {
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "id")
    var id: Int = 0
}

TicketDbDao
@道
接口(interface)TicketDbDao {
@Insert
fun insert(ticket: TicketDb)

@Query("SELECT * FROM ticket_table ORDER BY id DESC")
fun getAllTickets(): List<TicketDb>

}

这给我在日志中插入数据如下
2019-07-12 15:48:51.179 30262-30262/com.hardik.demos I/Hardik: Data :[TicketDb(ticketnumber=4214), TicketDb(ticketnumber=1123), TicketDb(ticketnumber=12), TicketDb(ticketnumber=1), TicketDb(ticketnumber=4214), TicketDb(ticketnumber=1123), TicketDb(ticketnumber=12), TicketDb(ticketnumber=1), TicketDb(ticketnumber=1), TicketDb(ticketnumber=1), TicketDb(ticketnumber=1)]

10-08 15:30