patloew / countries

An example Android app using Retrofit, Realm, Parceler, Dagger and the MVVM pattern with the data binding lib.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Adding a third tab and going back and forth crashes the app

comiclandapp opened this issue · comments

Thank you very much for sharing this code. I've been playing with it to learn DI, realm, and all that good stuff. When I add another 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

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.

Because he calls inject in onCreate() instead of onCreateView() when viewModel == null even though the documentation explicitly says that you need to call inject in onCreateView() like that.

Thank you very much, Zhuinden. That was the problem.

@Zhuinden You are right, thanks for the hint. I'm not that happy with the example anyway and will update it (hopefully) soon.