如何使用viewmodel在SQLite中更改数据后如何获取新数据?
FavoriteViewModel.Kt
class FavoriteViewModel(application: Application) : AndroidViewModel(application) {
private var favoriteEventList = MutableLiveData<MutableList<Favorite>>()
init {
favoriteEventList = getFavoriteEvent(application)
}
fun getFavorite(): LiveData<MutableList<Favorite>> = favoriteEventList
private fun getFavoriteEvent(context: Context): MutableLiveData<MutableList<Favorite>> {
val favoriteList = MutableLiveData<MutableList<Favorite>>()
val favorites: MutableList<Favorite> = mutableListOf()
favorites.clear()
context.database.use {
val result = select(Favorite.TABLE_FAVORITE)
val favorite = result.parseList(classParser<Favorite>())
favorites.addAll(favorite)
favoriteList.value = favorites
}
return favoriteList
}
fun removeFromFavorite(context: Context, param: String) {
try {
context.database.use {
delete(
Favorite.TABLE_FAVORITE, "(${Favorite.EVENT_ID} = {id})",
"id" to param
)
}
showToast(context, "Removed from favorite")
} catch (e: SQLiteConstraintException) {
showToast(context, "Error : ${e.localizedMessage}")
}
}
}
FavoriteFragment.Kt
override fun onResume() {
super.onResume()
val favoriteViewModel =
ViewModelProviders.of(this)[FavoriteViewModel::class.java]
favoriteViewModel.getFavorite().observe(this, Observer {
progressBar.gone()
favoriteList.clear()
favoriteList.addAll(it)
})
}
我尝试使用“ Anko SQLite”从SQlite显示和删除数据,这是可行的。但是,删除一些数据后,我没有从SQLite获取新数据。因此,在FavoriteFragment中仅显示旧数据。我必须重新打开FavoriteFragment才能显示新数据
将此代码放入“删除”按钮上的单击侦听器,而不是onResume
val favoriteViewModel =
ViewModelProviders.of(this)[FavoriteViewModel::class.java]
favoriteViewModel.getFavorite().observe(this, Observer {
progressBar.gone()
favoriteList.clear()
favoriteList.addAll(it)
})