如何在SQLite中使用viewmodel更改数据后如何获取新数据?

问题描述 投票:0回答:1

如何使用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才能显示新数据

android kotlin android-sqlite android-livedata android-viewmodel
1个回答
0
投票

将此代码放入“删除”按钮上的单击侦听器,而不是onResume

val favoriteViewModel =
        ViewModelProviders.of(this)[FavoriteViewModel::class.java]
    favoriteViewModel.getFavorite().observe(this, Observer {
        progressBar.gone()
        favoriteList.clear()
        favoriteList.addAll(it)
    })
© www.soinside.com 2019 - 2024. All rights reserved.