Search code examples
androidnullpointerexceptionandroid-tablayout

What is the cause of this NPE?


First, let's get things clear. NPE happens usually when a null element is being asigned a value. Funny enough, this is not what happens here, but I still get the NPE and I'm not sure what exactly is going wrong here.

I have a simple tabLayout in my MainActivity, which is not even hooked up with any fragments yet. I initialize and set it up like this:

ViewPager viewPager = new ViewPager(this);
TabLayout tabLayout = findViewById(R.id.tabsLayout);
tabLayout.setupWithViewPager(viewPager);

Then I use a custom method to set the Views of each tab like this:

tabLayout.addTab(tabLayout.newTab().setCustomView(initTabView(getResources().getDrawable(R.drawable.baseline_explore_black_18dp),
            getResources().getString(R.string.tab_map))), true);
tabLayout.addTab(tabLayout.newTab().setCustomView(initTabView(getResources().getDrawable(R.drawable.baseline_perm_identity_black_18dp),
            getResources().getString(R.string.tab_profile))));
tabLayout.addTab(tabLayout.newTab().setCustomView(initTabView(getResources().getDrawable(R.drawable.baseline_loyalty_black_18dp),
            getResources().getString(R.string.tab_offers))));
tabLayout.addTab(tabLayout.newTab().setCustomView(initTabView(getResources().getDrawable(R.drawable.qr_code_icon),
            getResources().getString(R.string.tab_scanner))));

And here is the method:

private View initTabView(Drawable tabIcon, String tabText) {
    View mainView = getLayoutInflater().inflate(R.layout.tab_layout, null);
    ImageView tabImageView = findViewById(R.id.tab_icon);
    TextView tabTextView = findViewById(R.id.tab_text);
    tabImageView.setImageDrawable(tabIcon);
    tabTextView.setText(tabText);
    return mainView;
}

I get the NPE on this line: tabImageView.setImageDrawable(tabIcon);, saying that its attempting to invoke the setImageDrawable method on a null object reference. How come the imageView is null, when I set it up two lines above? I am definitely missing something here, but don't know exactly what.


Solution

  • How come the imageView is null, when I set it up two lines above?

    findViewById() returns null if the view was not found in the layout hierarchy.

    You probably want to call mainView.findViewById() to search the just inflated view hierarchy instead of the activity view hierarchy.