Vishal
Vishal

Reputation: 41

Getting a null pointer exception when setting up the tab icons

I am trying to setup icons in the tabs, but I am keep getting null pointer exception.I am unable to understand as to why is happening?

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Log.d(TAG, "onCreate: starting");
    setupNavigationView();
    setupViewPager();

}

//Responsible for adding the 3 tabs:camera,main,message
private void setupViewPager(){
    SectionPagerAdapter sectionPagerAdapter = new SectionPagerAdapter(getSupportFragmentManager());
    sectionPagerAdapter.addFragment(new CameraFragment());
    sectionPagerAdapter.addFragment(new MainFragment());
    sectionPagerAdapter.addFragment(new MessagesFragment());
    ViewPager viewPager = findViewById(R.id.container);
    viewPager.setAdapter(sectionPagerAdapter);

    TabLayout layout = findViewById(R.id.tabs);
    layout.setupWithViewPager(viewPager);

    layout.getTabAt(0).setIcon(R.drawable.ic_camera);
    layout.getTabAt(1).setIcon(R.drawable.ic_instagram);
    layout.getTabAt(2).setIcon(R.drawable.ic_action_name);


}

Error:

  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
                                                                                Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.support.design.widget.TabLayout$Tab android.support.design.widget.TabLayout$Tab.setIcon(int)' on a null object reference
                                                                                   at android.vishal.instagramclone.MainActivity.MainActivity.setupViewPager(MainActivity.java:47)
                                                                                   at android.vishal.instagramclone.MainActivity.MainActivity.onCreate(MainActivity.java:31)

Upvotes: 0

Views: 2408

Answers (2)

Subrata Mondal
Subrata Mondal

Reputation: 852

To get the view either use:

layout.getChildAt(0).getChildAt(0).setIcon(R.drawable.ic_camera);
layout.getChildAt(0).getChildAt(1).setIcon(R.drawable.ic_instagram);

or

layout.getChildAt(0).findViewById(R.id.your_camera_tab_id).setIcon(R.drawable.ic_camera);
layout.getChildAt(0).findViewById(R.id.your_instagram_tab_id).setIcon(R.drawable.ic_instagram);

layout.getChildAt(0) returns the ViewGroup holding the Tabs.

Upvotes: 1

Fazal Hussain
Fazal Hussain

Reputation: 1127

You are facing this issue because you have not added tabs and try to set icon

//Add tabs icon with setIcon() or simple text with .setText()
 tabLayout.addTab(tabLayout.newTab().setIcon(R.mipmap.ic_home));
 tabLayout.addTab(tabLayout.newTab().setIcon(R.mipmap.ic_profile));
 tabLayout.addTab(tabLayout.newTab().setIcon(R.mipmap.ic_settings));

For further details check the link below

https://gist.github.com/faizsiddiqui/9af9cea9051335e1ad3f

Upvotes: 5

Related Questions