Android databinding and viewmodel not working
Asked Answered
S

2

5

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

Sussna answered 11/12, 2017 at 9:21 Comment(1)
try android:text="@{viewModel.worksheet.getShort_text + ?}"Clericals
L
7

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);
Ledda answered 11/12, 2017 at 9:26 Comment(0)
B
2

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()

Barbuto answered 25/12, 2019 at 9:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.