Cannot create an instance of custom ViewModel

前端 未结 6 1447
孤街浪徒
孤街浪徒 2020-12-11 01:26

I am using dagger2 library. whenever I am trying to run my project is says not able to create instance of view model class.

main activity where I am trying to create

相关标签:
6条回答
  • 2020-12-11 01:38

    I'm a proficient Android developer and I have used ViewModel 100s of times with no issue. Today I came across this issue. Spent hours and scrolled through various SO posts. Didn't get solved.

    Then I saw that the package name in which I have the ViewModel contains new. Like this:

    com.myapp.myfeature.new.feature

    I changed new to neww for testing like this: com.myapp.myfeature.neww.feature

    and it worked! I hope someone find it useful.

    0 讨论(0)
  • 2020-12-11 01:43

    Extend AndroidViewModel from your ViewModel class.

    public class YourViewModel extends AndroidViewModel {
    
        public YourViewModel(Application application) {
            super(application);
    
            //Todo: ...
        }
    }
    
    0 讨论(0)
  • 2020-12-11 01:44

    Need to add below code in all activity if you use multiple activity

    AndroidInjection.inject(this);
    
    0 讨论(0)
  • 2020-12-11 01:51

    The solution for me was injecting the activity because I was using Dagger2

            AndroidInjection.inject(this);
    
    0 讨论(0)
  • 2020-12-11 01:52

    Instead of:

    mViewModel = ViewModelProviders.of(this).get(MoviesDataViewModel.class);
    

    Perform:

    mViewModel = ViewModelProviders.of(this, viewModelFactory).get(MoviesDataViewModel.class);
    
    0 讨论(0)
  • 2020-12-11 01:52

    Replace:

    private MoviesDataViewModel mViewModel;
    

    with:

    MoviesDataViewModel mViewModel;
    
    0 讨论(0)
提交回复
热议问题