I'm looking at the new Data Binding plugin for Android and trying to integrate it in a project.
While reading about creating observable objects, i encountered the ObservableFields documentation that involves using self-contained observable objects example from documentation :
public class User extends BaseObservable {
   public final ObservableField<String> firstName =
       new ObservableField<>();
   public final ObservableField<String> lastName =
       new ObservableField<>();
   public final ObservableInt age = new ObservableInt();
}
Above snippet would be a replacement of:
private static class User extends BaseObservable {
   private String firstName;
   private String lastName;
   @Bindable
   public String getFirstName() {
       return this.firstName;
   }
   @Bindable
   public String getFirstName() {
       return this.lastName;
   }
   public void setFirstName(String firstName) {
       this.firstName = firstName;
       notifyPropertyChanged(BR.firstName);
   }
   public void setLastName(String lastName) {
       this.lastName = lastName;
       notifyPropertyChanged(BR.lastName);
   }
}
Which is significantly less code; But when using Observable Fields and reference then from the XML layout like such:
<layout xmlns:android="http://schemas.android.com/apk/res/android">
   <data>
       <variable name="user" type="com.example.User"/>
   </data>
   <LinearLayout
       android:orientation="vertical"
       android:layout_width="match_parent"
       android:layout_height="match_parent">
       <TextView android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="@{user.lastName}"
           android:id="@+id/lastName"/>
   </LinearLayout>
</layout>
I am getting this error:
../../databinding/ActivityMainBinding.java
Error:(127, 20) error: cannot find symbol variable lastName 
And that is not verbose at all; Not using ObservableFields works like a charm.
Documentation reference
Anyone facing this issue ? Thoughts?
This looks like a bug on our end. I heard adding @Bindable fixes the issue but data binding should be able to find it w/o a Bindable annotation. I've created a bug internally, thanks.
ObservableField needs to be annotated with the @Bindable annotation for it to compile.
The Source for the Bindable annotation states:
this is necessary for java analyzer to work
So it ends up looking like this:
public class User extends BaseObservable {
   @Bindable
   public final ObservableField<String> firstName =
       new ObservableField<>();
   @Bindable
   public final ObservableField<String> lastName =
       new ObservableField<>();
   @Bindable
   public final ObservableInt age = new ObservableInt();
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With