I get a null pointer exception when I try to programmatically switch tabs from tablayout inside a fragment,
So, I have a main lesson that has a tab (4 tabs), each tab has a presentation pager containing a fragment, and each of these fragments has a tab layout (number of tabs) with a presentation pager containing a fragment, I can switch layout tabs main activity tab from any fragment like this
TabLayout tabLayout = MainActivity.tabLayout; TabLayout.Tab tab = tabLayout.getTabAt(2); tab.select();
but if I try to change the tabs of one of the fragments in the same way, I get a null pointer
TabLayout tabLayout2 = tabFragOne.tabLayout; TabLayout.Tab tab2 = tabLayout2.getTabAt(2); tab2.select();
this happens only if I press the button in question when the application opens first, which indicates that the reason for this is because the fragment has not yet been attached or created,
for example, if I look at the snippets tab that I want to go to, and then return to the main activity and click on the button in question, it will work. Does anyone know a better way to fix this?
Ok ive found that half of this question is actually im using a view pager adapter, the question here sheds a lot of light on my problem
source share