title: Change tab index of fragments with tabs programmatically
body: <p>I'm getting a null pointer exception when trying to switch tabs programmatically of a tablayout inside a fragment,</p>
  
  <p>So I have my main activity that has a tab layout (4 tabs) each tab has a view pager holding a fragment, and each of these fragments has a tab layout (x amount of tabs) with a view pager holding a fragment, 
  i can switch the tabs of my main activity tab layout from any fragment like this </p>
  
  <pre><code>TabLayout tabLayout = MainActivity.tabLayout;
  TabLayout.Tab tab = tabLayout.getTabAt(2);
  tab.select();
  </code></pre>
  
  <p>but if i try to change the tabs of one of the fragments in the same way i get a null pointer</p>
  
  <pre><code>TabLayout tabLayout2 = tabFragOne.tabLayout;
  TabLayout.Tab tab2 = tabLayout2.getTabAt(2);
  tab2.select();
  </code></pre>
  
  <p>it only happens if I click the button in question when the app first opens, which suggests that the reason for it is that the fragment hasn't been attached or created yet,</p>
  
  <p>for instance if i scroll across to the fragments tab i want to switch to, and then go back to the main activity and press the button in question it will work.
  does anyone know the best way to fix this?</p>
  
  <p>Ok ive found half the crux to this question is actually that im using a view pager adapter, a question <a href="https://stackoverflow.com/questions/7951730/viewpager-and-fragments-whats-the-right-way-to-store-fragments-state">here</a> sheds a lot of light on my issue</p>