title: Android: Why is onTabSelected being called when tabs are created?
body: <p>When the action bar has tabs, I've noticed that onTabSelected is called when the activity loads on screen.  It also is being called whenever an orientation change occurs.  My code queries the database depending on the tab being selected, and displays the query results to the loaded layout.</p>
  
  <p>My problem is when saving tab state, and the current selected tab is 1 or higher, on restore state, since onTabSelected is called by default on the 0 tab, it will be called again when restored state tab is 1 or higher.  This makes database query on tab 0 useless.  </p>
  
  <p>How to configure android that onTabSelected isn't called on tab creation or at least detect that this call is default and not user triggered?</p>
  
  <pre><code>@Override
  public void onTabSelected(Tab tab, FragmentTransaction ft) {
      int tabPos = tab.getPosition();
      switch(tabPos) {
      case 0:
          // query database and display result
          break;
      case 1:
          // a different query and display result
          break;
      case 2: ...
      }
  }
  
  @Override
  public void onRestoreInstanceState(Bundle savedInstanceState) {
      if(savedInstanceState.containsKey(STATE_SELECTED_TAB)) {
          getActionBar().setSelectedNavigationItem(savedInstanceState.getInt(STATE_SELECTED_TAB));
      }
      super.onRestoreInstanceState(savedInstanceState);
  }
  
  @Override
  public void onSaveInstanceState(Bundle outState) {
      outState.putInt(STATE_SELECTED_TAB, getActionBar().getSelectedNavigationIndex());
      super.onSaveInstanceState(outState);
  }
  </code></pre>
  
  <p><strike>
  <strong>Added complication:</strong>
  When the current selected tab is 0, and the orientation changes, onTabSelected is still called twice!  Once when the tabs are initially created, and 2nd time when onRestoreState restores the saved tab selected state, even though it is 0.
  </strike></p>
  
  <p>What I originally supposed was that onTabSelected was called twice, but I was mistaken.  It was my fragment onCreateView being called twice, some errors in fragment transaction that added the same fragment twice on orientation change.   onTabSelected is called once, and restore state calls onTabReselected is called too when the restored tab is also 0.</p>
  
  <hr>
  
  <p>After scouring SO and google, I've found this question to have similar cause of problem.
  <a href="https://stackoverflow.com/questions/19084931/creating-actionbar-tab-also-calling-its-selecttab-functions">Creating ActionBar tab also calling its selectTab functions</a></p>