Search code examples
androidkotlinandroid-databindingandroid-viewmodel

My viewmodel data is not being bound to edittext


I have bounded a viewmodel to an activity and that is working fine, but in another activity where I bound my viewmodel is not showing any data. Here is my viewmodel variable declaration in my activity:

<layout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    >
    <data>
        <variable name="profileViewModel"
            type="com.kreeti.gogal.ui.profile.ProfileViewModel"
            />
    </data>
   ......
   <EditText
       style="@style/convertible_edit_text"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:drawableEnd="@drawable/ic_edit"
       android:text="@={profileViewModel.firstName}"/>

here is my viewmodel:

class ProfileViewModel constructor(
    val repository: ProfileRepository,
    private val mContext: Context
) : ViewModel() {
    var firstName: String? = null
    ....
init {
      Coroutines.main {
           try {
               repository.getProfileDetails().let {
                   firstName = it.data.first_name  // Here I am fetching the data
                }
           ....
     }
}

this is my activity class

class EditProfile : AppCompatActivity(), ResponseListener {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val networkConnectionInterceptor = NetworkConnectionInterceptor(this)
        val api = BaseApi.invoke(networkConnectionInterceptor, AuthorizedApi::class.java)
        val profileRepository = ProfileRepository(api)
        val factory = ProfileViewModelFactory(profileRepository, this)
        val viewModel = ViewModelProvider(this, factory).get(ProfileViewModel::class.java)

        val binding: ActivityEditProfileBinding = DataBindingUtil.setContentView(this, R.layout.activity_edit_profile)
        binding.profileViewModel = viewModel
     }

I cannot understand why my edittext is not getting the data


Solution

  • If you're using databinding in your xml it should be : android:text="@{profileViewModel.firstName}" instead of android:text="@={profileViewModel.firstName}" other than that I don't see any problem.

    You also might be interested in this codelab

    PS: profileViewModel shouldn't have any reference to context as it might create some bug, if you really need context you can use AndroidViewModel instead of ViewModel implementation. AndroidViewModel gives you access to ApplicationContext.