【发布时间】:2021-12-21 18:22:00
【问题描述】:
@Entity 生物
我正在尝试更新数据库中的 name 属性。
@Entity(primaryKeys = ["name"])
data class Creature(
@ColumnInfo(defaultValue = "New Creature") val name: String
)
@Dao CreatureDao
更新名称的查询在这里,在 DAO 中。
@Dao
interface CreatureDao {
[...]
// update creature name
@Query("UPDATE Creature SET name=:newName WHERE name=:oldName")
fun updateCreatureName(oldName: String, newName: String)
}
我的存储库
我的视图模型通过我的存储库进行查询
class MyRepository(private val creatureDao: CreatureDao) {
[...]
// update creature name
@Suppress("RedundantSuspendModifier")
@WorkerThread
suspend fun updateCreatureName(oldName: String, newName: String) {
creatureDao.updateCreatureName(oldName, newName)
}
}
SharedViewModel
这是我的视图模型调用更新名称属性的地方
class SharedViewModel(
private val repository: MyRepository
) : ViewModel() {
[...]
fun updateCreatureName(oldName: String, newName: String) {
viewModelScope.launch { repository.updateCreatureName(oldName, newName) }
}
}
关于片段
这个视图模型的 updateCreatureName() 方法在 nameTextInputEditText 改变时从 AboutFragment 调用...
class AboutFragment() : Fragment() {
[...]
// update creature record when creature name is edited
binding.nameTextInputEditText.addTextChangedListener(object : TextWatcher {
private lateinit var oldName: String
private lateinit var newName: String
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
oldName = s.toString()
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
newName = s.toString()
}
override fun afterTextChanged(s: Editable?) {
sharedViewModel.updateCreatureName(oldName, newName)
}
})
}
}
问题
我收到错误
java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
当我尝试启动活动片段时。我该如何运行
override fun afterTextChanged()
离开主线程?
【问题讨论】:
标签: android-studio android-room kotlin-coroutines android-textinputedittext addtextchangedlistener