Domin
Domin

Reputation: 1145

Databinding - ObservableField<String> not updating view

I have simple app - Button - which fetches data from rest api and a TextView where this data is displayed. I'm using MVVM architectural pattern. When ViewModel receives callback with fetched data I set it up to an ObservableField. Unfortunately it doesn't update text on the screen, but whenever I rotate device data is being updated on the screen.

OK, enough talking, I'll show you the code:

ViewModel

public class MyViewModel extends ViewModel{

private ObservableField<String> name = new ObservableField<>();

@Override
public void onListReceived(String username) {
    super.onListReceived(list);
    name.set(username);
}

public String getName() {
    return name.get();
}}

and in XML:

<TextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@{viewModel.name}"
        tools:text="some text"/>

As far as I read, I think it should be '=' in this line android:text="@{viewModel.name}" between '@' and '{', but when I add it, clean project and rebuild this, I got an error that Cannot resolve DataBindingComponent.

Any ideas?
Thanks in advance!

Upvotes: 4

Views: 2112

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006584

Remove the getName() method, and make name be public. Or, have getName() return name, not name.get().

The data binding system needs to be working directly with the Observable. Right now, your Observable is hidden from data binding, and so data binding has no way of registering an observer and knowing when the data changes.

As far as I read, I think it should be '=' in this line android:text="@{viewModel.name}" between '@' and '{',

That syntax (@={viewModel.name}) is for two-way data binding. Since the user cannot enter data into a TextView, that is not needed here.

Upvotes: 7

Related Questions