我在Android Room上还很陌生,它使用的LiveData我也不熟悉。我注意到在教程中,返回的数据使用的是LiveData
包装器,如下所示:
@Dao
interface PersonDao {
@Query("SELECT * FROM person")
fun getAll(): LiveData<List<Person>>
}
然后读取数据,我使用此代码:
class PersonListActivity: AppCompatActivity() {
List<Person> personList = listOf()
init {
val db = RoomDatabase.getDatabaseInstance()
db.personDao.getAll().observe(this, Observe<List<Person>> { data ->
personList = data
})
}
}
问题是IDE引发错误“类型不匹配”。必需:LifeCycleOwner。找到:PersonListActivity。我不了解这些教程如何随意将“ this”提供给observe owner参数。我还尝试将context
和applicationContext
提供到owner参数,但它不起作用。
[检查了LifeCycleOwner
类后,我尝试添加LifeCycleOwner实现。但是随后该类要求实现getLifeCycle()
函数。所以我回到零。
class PersonListActivity: AppCompatActivity(), LifeCycleOwner {
List<Person> personList = listOf()
init {
val db = RoomDatabase.getDatabaseInstance()
db.personDao.getAll().observe(this, Observe<List<Person>> { data ->
personList = data
})
}
override fun getLifeCycle() {
// what should I return here??????
}
}
为什么我阅读的所有有关LiveData的教程都根本没有提及LifeCycleOwner?我在这里使用错误的观察功能吗?
public abstract class LiveData<T> {
...
@MainThread
public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer) { ... }
...
}
由于版本1.1.0(不稳定的发行版除外),androidx.appcompat:appcompat
实施AppCompatActivity
(请参阅LifecycleOwner
)。因此,您可以在调用时使用ComponentActivity
:
this
不执行任何其他操作。
此外,我将在db.personDao.getAll().observe(this, Observe<List<Person>> { data ->
personList = data
})
中移动这些行。