无法创建ViewModel类的实例(无法启动活动ComponentInfo) [英] Cannot create an instance of ViewModel class (Unable to start activity ComponentInfo)
本文介绍了无法创建ViewModel类的实例(无法启动活动ComponentInfo)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
- Cannot create an instance of custom ViewModel
- 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 {
@Override
protected 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);
}
});
}
}
推荐答案
引用 AndroidViewModel
的文档:
Quoting the documentation for AndroidViewModel
:
子类必须具有一个接受Application作为唯一参数的构造函数.
Subclasses must have a constructor which accepts Application as the only parameter.
您的构造函数不满足该要求.
Your constructor does not meet that requirement.
要么:
-
从
HomeViewModel
或
创建 a ViewModelProvider.Factory
可以构建您的HomeViewModel
实例,并将该工厂与ViewModelProviders.of()
Create a ViewModelProvider.Factory
that can build your HomeViewModel
instances, and use that factory with ViewModelProviders.of()
这篇关于无法创建ViewModel类的实例(无法启动活动ComponentInfo)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文