I've been playing with this github repo: https://github.com/patloew/countries to learn DI, mvvm, realm, and all that good stuff. When I add a third tab in MainAdapter.java:
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new AllCountriesFragment();
case 1:
return new FavoriteCountriesFragment();
//case 2:
// return new FavoriteCountriesFragment();
}
return null;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return res.getString(R.string.tab_title_all);
case 1:
return res.getString(R.string.tab_title_favorites);
//case 2:
// return res.getString(R.string.tab_title_favorites);
}
return null;
}
I get an exception in BaseFragment.java:
protected final View setAndBindContentView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState, @LayoutRes int layoutResID) {
if (viewModel == null)
throw new IllegalStateException("viewModel must already be set via injection");
java.lang.IllegalStateException: viewModel must already be set via injection
The third fragment doesn't have to be identical to the second, it's actually a completely new fragment. Commenting out the viewModel in onDestroyView
//viewModel = null;
avoids the crash but strange things happen afterwards.
Any pointers on what to do to help me understand the bigger picture and fix this? The question really is why isn't the viewModel being injected on a tab change. Thanks a lot.