Android Room-插入有效,但select不返回任何值

时间:2019-07-10 12:34:27

标签: android kotlin android-room

我想通过会议室从数据库中选择数据。

这是我的代码。

数据库

@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

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

}

视图模型

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");

3 个答案:

答案 0 :(得分:1)

我认为您在从会议室检索数据时遇到问题。以下代码未经测试,但是为您提供指导,我正在尝试解决。检查并回复评论是否有效。

@Dao
interface TicketDbDao {

    @Insert
    suspend fun insert(ticket: TicketDb)

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

我认为会议室查询返回列表数据,但是您正在尝试获取livedata对象。因此,请更改为 dao 操作的以下代码。

@Dao
interface TicketDbDao {

    @Insert
    suspend fun insert(ticket: TicketDb)

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

TicketRepository

class TicketRepository (private val ticketDbDao: TicketDbDao) {

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

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

现在进入您的视图模型

var ticketRepository: TicketRepository

private val _allTickets = MutableLiveData<List<TicketDb>>() // backing property should be used for updating values

val allTickets: LiveData<List<TicketDb>> = _allTickets // mutable live data should not be exposed

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

}

fun getTicketValues(){
    _allTickets.value = ticketRepository.allTickets
}

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

答案 1 :(得分:1)

我尝试了相同的代码,但改动很小,可以正常工作

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")

    }
}

MyDatabase

@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 @道 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)]

答案 2 :(得分:1)

您必须观察活动或片段中的实时数据,例如

 ViewModel.allTickets.observe(this, new Observer<>() {
        @Override
        public void onChanged() {
          
        }
    });