0

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.

  • "Each subclass therefore has to call the following code in onCreateView() `if(viewModel == null) { fragmentComponent().inject(this); }`" are you doing that? – EpicPandaForce Aug 11 '17 at 09:24
  • Indeed the repo does that. Thanks for the suggestion. I've found something else I'm looking into: a fix for fragment restoration [link](http://speakman.net.nz/blog/2014/02/20/a-bug-in-and-a-fix-for-the-way-fragmentstatepageradapter-handles-fragment-restoration/). I'm hopeful it might help and will update if/when I find a fix. Best regards. – Tony Montes Aug 12 '17 at 14:39
  • This is only relevant if you manipulate the fragments in the pager adapter. – EpicPandaForce Aug 12 '17 at 14:48

1 Answers1

1

Replacing FragmentPagerAdapter with FixedFragmentStatePagerAdapter from Adam's blog seemed to avoid the problem (viewModel = null). However, as you correctly pointed out, fragmentComponent().inject(this) was not being called in OnCreateView but rather in onCreate. All good now. Thank you very much for your input.