Sombrero
Sombrero

Reputation: 47

Weird DataBinding in Android

I try to figure out how to work with data binding in Android and met a strange problem. When I put my ViewModel class in some package, generated ActivityMainBinding can't see it and say: error: package ViewModels does not exist. But if I put it in the root package, then trouble disappears. Is it my mistake or some kind of bug?

Code:

activity_main.xml

<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">

<data>
    <variable
        name="DataContext"
        type="com.example.sombrero.bluem.ViewModels.MainViewModel" />
</data>
...

MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
    MainViewModel mainViewModel = ViewModelProviders.of(this).get(MainViewModel.class);
    binding.setDataContext(mainViewModel);
}

MainViewModel is just empty class for now.

Upvotes: 0

Views: 101

Answers (2)

DisplayName
DisplayName

Reputation: 58

I ran into this as well. Thanks to tynn for answering my question.

According to tynn, it is because we didn't follow the oracle naming conventions for packages. The package name should be all lowercase. Changing "ViewModels" to "viewmodels" fixed it for me.

Upvotes: 1

Khemraj Sharma
Khemraj Sharma

Reputation: 58964

Extend MainViewModel from ViewModel

public class MainViewModel extends ViewModel {

}

Read about LiveData

Upvotes: 0

Related Questions