Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android databinding and viewmodel not working

I have a ViewModel class, and a Model class in that.

class WorksheetViewModel {

    private Worksheet worksheet;

    public Worksheet getWorksheet() {
        return worksheet;
    }

    public void setWorksheet(Worksheet worksheet) {
        this.worksheet = worksheet;
        if (worksheet != null) showButtons();

        Logger.E(worksheet.getShort_text());
    }

this is working here: Logger.E(worksheet.getShort_text());

and in my xml

<import type="android.view.View" />

<variable
    name="viewModel"
    type="viewmodels.WorksheetViewModel" />

..

and a textview with:

android:text="@{viewModel.worksheet.short_text + `?`}"

My probleme is, viewModel.worksheet.short_text is allways null. Why?

binding.setViewModel(new WorksheetViewModel());
binding.executePendingBindings();

Also I have all the

Worksheet extends BaseObservable

and

  @Bindable
    public String getShort_text() {
        return short_text;
    }

in my Worksheet

like image 944
lacas Avatar asked Dec 11 '17 09:12

lacas


Video Answer


2 Answers

Problem is you are just setting ViewModel in binding binding.setViewModel(new WorksheetViewModel()); but WorksheerViewModel also have Worksheet object, and it is blank.

So this should be

WorksheetViewModel viewModel = new WorksheetViewModel();
viewModel.setWorksheet(new WorkSheet('short text value'))
binding.setViewModel(viewModel);
like image 144
Ravi Avatar answered Oct 07 '22 18:10

Ravi


If any one get error in binding.setViewmodel() it resolve by binding.setViewmodel(), In setViewmodel, Viewmodel is variable name which is given in layout.

e.g

<data>
     <variable
        name="userviewmodel"
        type="com.example.mvvmtest.viewmodel.LoginViewModel" />
</data>

Than use, binding.setUserviewmodel()

like image 43
shubham Lochan Avatar answered Oct 07 '22 18:10

shubham Lochan