Search code examples
androidandroid-roomkotlin-coroutinesandroid-livedatamutablelivedata

LiveData, Room persistant Ui is not updated


I am building an android app using Room for the data persistence and LiveData.

I have multiple fragments and viewModel.

When i start the app and land on the MainActivityView, I am also placing a call to retrieve the userinformation and save it in the Room Database. This is working fine.

Then when I access the user profile fragement, I was expecting to see the user information displayed but nothing shows up. The data are in the database but it seems that the UI is not refreshed.

In my User Profile fragement, I am doing this:

override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {


        viewModel.getUserInfo().observe(viewLifecycleOwner, object: Observer<UserProfileResp?> {
            override fun onChanged(t: UserProfileResp?) {
                getName(t?.firstName, t?.lastName)?.let {
                    binding.userEt.apply {
                        setText(it)
                        showTopText()
                    }
                }

the getUserInfo is defined in my UserProfileViewModel as below:

fun getUserInfo(): MutableLiveData<UserProfileResp?> = appRepository.getUserInfo()

the AppRepository as :

override fun getUserInfo(): MutableLiveData<UserProfileResp?> =  userInformationDb.getUserInfo()

and the call to the Db as :

@Query("SELECT userinfo from usertable WHERE username='USER'") fun getUserInfo(): MutableLiveData<UserProfileResp?>

I have created also the setUserInfo but it's called earlier in the code when I am loading the MainActivity. The goal is to let the mainActivity or my homepage fragment requesting through their viewModel the UserInformation and save it in the Db. Which is working but it seems that observing in the profile fragement is not working at all.

Any idea ?


Solution

  • May I see your UserProfileResponse class? It is probably because you have firstName, lastName fields on UserProfileResponse class but on your SQL code, you are not trying to get these fields.

    Instead of SELECT userinfo ...., you should write SELECT * ... or all the fields you would like to receive. Quick example in below:

    @Query("SELECT * from usertable WHERE username='USER'") fun getUserInfo(): MutableLiveData<UserProfileResp?>
    

    Also note: Make sure about your user's username. Because WHERE is not case sensitive. If you are going to save username, better to make all lowercase while saving the data and getting the data.