The class cannot inherit from the AndroidViewModel, why?

孤街醉人 提交于 2021-01-29 02:57:18

问题


I try create a new class that inherits from AndroidViewModel, like this

public class LoginViewModel extends AndroidViewModel {

       public LoginViewModel() {}
...

But I get this message in the ide:

There is no default constructor available in 'android.arch.lifecycle.AndroidViewModel'

My happen this?

My graddle looks like this:

...
    implementation 'android.arch.lifecycle:extensions:1.1.1'
...

Any idea?

Thanks


回答1:


You will need to add super call to AndroidViewModel class when inheriting from it. AndroidViewModel class contains default constructor having Application class as variable, so you should change your implementation as below :

public class LoginViewModel extends AndroidViewModel {

   public LoginViewModel(Application application) {
       super(application);
       // Do rest of your stuff here ...
   }
...

Default implementation of AndroidViewModel class states that :

Application context aware ViewModel.

Subclasses must have a constructor which accepts Application as the only parameter.




回答2:


AndroidViewModel has only one public constructor that takes an Application as parameter. You must call this from your constructor:

public LoginViewModel(Application app) {
    super(app);
}



回答3:


https://developer.android.com/reference/android/arch/lifecycle/AndroidViewModel

Subclasses must have a constructor which accepts Application as the only parameter.



来源:https://stackoverflow.com/questions/54462295/the-class-cannot-inherit-from-the-androidviewmodel-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!