我在我的项目中使用MVVM,Retrofit,liveData但我在看到这些链接之前得到了这个错误
> @L_403_0@
> Cannot create an instance of class ViewModel
错误
java.lang.RuntimeException: Unable to start activity ComponentInfo{ir.orangehat.movIEinfo/ir.orangehat.movIEinfo.application.home.HomeActivity}: java.lang.RuntimeException:Cannot create an instance of class ir.orangehat.movIEinfo.application.home.Homeviewmodel
这是我的viewmodel,我认为问题出在我的构造函数中
public class Homeviewmodel extends AndroIDviewmodel {private MovIERepository movIERepository;public Homeviewmodel(@NonNull Application application, Context context, lifecycleOwner lifecycleOwner) { super(application); movIERepository = new MovIERepository(lifecycleOwner, context);}liveData<List<MovIE>> getMovIEs() { return movIERepository.getMovIEs();}}
知识库
public class MovIERepository extends BaseRepository {private lifecycleOwner lifecycleOwner;private MovIEAPI movIEAPI;private MovIEDatabaseHelper movIEDatabaseHelper;public MovIERepository(lifecycleOwner lifecycleOwner, Context context) { this.lifecycleOwner = lifecycleOwner; movIEAPI = getRetrofitHelper().getService(MovIEAPI.class); movIEDatabaseHelper = new MovIEDatabaseHelper(context);}public liveData<List<MovIE>> getMovIEs() { liveData<List<MovIE>> movIEsliveData = movIEAPI.getMovIEList(); movIEsliveData.observe(lifecycleOwner, new Observer<List<MovIE>>() { @OverrIDe public voID onChanged(@Nullable List<MovIE> movIEArrayList) { movIEDatabaseHelper.Save(movIEArrayList); } }); return movIEDatabaseHelper.getAll();} }
活动类
public class HomeActivity extends AppCompatActivity {@OverrIDeprotected voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentVIEw(R.layout.activity_main); // the error is here Homeviewmodel homeviewmodel = viewmodelProvIDers.of(this).get(Homeviewmodel.class); homeviewmodel.getMovIEs().observe(HomeActivity.this, new Observer<List<MovIE>>() { @OverrIDe public voID onChanged(@Nullable List<MovIE> movIEArrayList) { String str = null; if (movIEArrayList != null) { str = Arrays.toString(movIEArrayList.toArray()); } Log.e("movIEs", str); } });}
}
我应该在我的项目和定制工厂中使用Dagger吗?
解决方法:
引用the documentation for AndroidViewModel
:
Subclasses must have a constructor which accepts Application as the only parameter.
您的构造函数不符合该要求.
或者:
>从Homeviewmodel中删除Context上下文和lifecycleOwner lifecycleOwner构造函数参数,或
>创建可以构建Homeviewmodel实例的a ViewModelProvider.Factory
,并将该工厂与viewmodelProvIDers.of()一起使用
以上是内存溢出为你收集整理的android – 无法创建ViewModel类的实例(无法启动活动ComponentInfo)全部内容,希望文章能够帮你解决android – 无法创建ViewModel类的实例(无法启动活动ComponentInfo)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)