Hi Adam,
You can wrap your RealmObject as a ViewModel & use the bindable annotation, here is an example.
Model:
public class RealmBook extends RealmObject {
@PrimaryKey
private String title;
private int price;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
ModelView extending BaseObservable
public class BookViewModel extends BaseObservable {
private final RealmBook realmBook;
public BookViewModel(RealmBook model) {
this.realmBook = model;
}
@Bindable
public String getTitle() {
if (realmBook.isValid()) {
return realmBook.getTitle();
}
return "";
}
@Bindable
public int getPrice () {
return realmBook.getPrice();
}
public void setTitle(String title) {
realmBook.setTitle(title);
notifyPropertyChanged(BR.title);
}
public void setPrice (int price) {
realmBook.setPrice(price);
notifyPropertyChanged(BR.price);
}
}
you then associate your ViewModel with the FormBinding
bookViewModel = new BookViewModel(realm.where(RealmBook.class).findFirst());
mBinding.setRealmBook(bookViewModel);
To reflect changes from Realm to the ViewModel you can register a listener
// listen for changed
realm.addChangeListener(new RealmChangeListener() {
@Override
public void onChange() {
bookViewModel.notifyChange();
}
});
To save changes to Realm, you can have a button save for example that create a write transaction.
public void onSave (View v) {
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
// We don't have two way data binding
bookViewModel.setTitle(mBinding.txtTitle.getText().toString());
bookViewModel.setPrice(Integer.parseInt(mBinding.txtPrice.getText().toString()));
}
});
}
Cheers,
--
Nabil Hachicha