Silly Things I Forget #1 – Android DataBinding

Welcome to the first edition of “Silly Things I forget”. This is the first of possibly many many posts to come as a way to remember things that I usually forget while writing code. I end up possibly googling for hours for the the solution very few blogs actually mention. Maybe they take it for granted that the solution is a given? Who knows.

Either way if you stumble on this and the next ones, I hope you find them as useful as I definitely know I will.

When using two-way databinding in Android, the usual rituals are performed.

1. The <layout> tags are added to your new layout to declare it for DataBinding.

2. The <data> tags are added followed by your ViewModel declaration within the tags:

<variable
    name="viewModel"
    type="my.app.ViewModel" />

3. I make sure my view widgets are tagged with two-way databinding declarations:

android:text="@={viewModel.firstName}"
android:text="@={viewModel.lastname}"
android:text="@={viewModel.emailAddress}"

4. My Bindable fields are declared in my ViewModel together with my property registry:

    @Bindable
    var firstName = ObservableField<String>()
    @Bindable
    var lastName = ObservableField<String>()
    @Bindable
    var emailAddress = ObservableField<String>()
    
    private val callbacks = PropertyChangeRegistry()

5. At this point I would assume that I should be getting my data back easily from my ui to my view model. But no, every field is always null. And the most annoying thing is no amount of debugging here will help.

The crucial line that I always miss? Binding my ViewModel declared in xml, to my actual ViewModel I’ve declared in code. without this, the above code is useless. So i need to add it!!!

//bind my viewmodel above:
binding.viewModel = viewModel

That’s it! I ALWAYS forget this line. It’s so trivial but without this, the above code just sits there and as I said before, debugging won’t help solve this problem. So next time values appear null even though everything appears to be setup correctly, don’t forget this line.