Android two way data binding with room table models

Viewed 1948

So I have room model classes annotated with @Entity annotation which contain fields annotated with @ColumnInfo.

I also have a view that binds to the object of this model:

   <EditText
        android:id="@+id/sadfadsdfasd"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center"
        android:hint="@string/assdsa"
        android:inputType="text"
        android:text="@={fuelPrice.modification}" />

Like this it works when displaying EditText. It shows value from my model, but when I modify EditText, that modification is not being stored in my object even though I use @= signs which indicate two way binding.

So if I understand correctly, I can't really use POJO with simple primitive fields for two way data binding and instead I should have all fields as observables of required type or fields wrapped in LiveData?

If above case is true, does that mean that to have two way binding for room entities, I have to create separate class for each entity which would implement all the observable fields and update my entity object accordingly? Or is there a simplier solution?

EDIT Above case was false. Seems like two way binding does work for simple POJO classes with appropriate getters and setters.

2 Answers

AFAIK I just tested it, it should work without ObservableField given that modification is a private field with standard getters and setters. Using

android:text="@={fueldPrice.modification}"

and

class FuelPrice {
    private String modification;

    public String getModification() {
        return modification;
    }

    public String setModification(String modification) {
        this.modification = modification;
    }
}

It also works if you just use a public field

class FuelPrice {
    public String modification;
}

you can use observableField as following:

public class FuelPrice {
  public ObservableField<String> modification = new ObservableField<>();
  public TextWatcher watcher = new TextWatcherAdapter() {
    @Override public void afterTextChanged(Editable s) {
      if (!Objects.equals(modification.get(), s.toString())) {
        modification.set(s.toString());
      }
    }
  };
}

and update your XML as following:

 <EditText
    android:id="@+id/sadfadsdfasd"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:gravity="center"
    android:hint="@string/assdsa"
    android:inputType="text"
    android:addTextChangedListener=”@{fuelPrice.watcher}” />

reference:

Two-way Android Data Binding

.

Related