title: Android. Fragment getActivity() sometimes returns null
body: <p>In developer console error reports sometimes I see  reports with NPE issue. I do not understand what is wrong with my code. On emulator and my device application works good without forcecloses, however some users get NullPointerException in fragment class when the getActivity() method is called.</p>
  
  <p>Activity</p>
  
  <pre><code>pulic class MyActivity extends FragmentActivity{
  
      private ViewPager pager; 
      private TitlePageIndicator indicator;
      private TabsAdapter adapter;
  
      @Override
      public void onCreate(Bundle savedInstanceState) {
          pager = (ViewPager) findViewById(R.id.pager);
          indicator = (TitlePageIndicator) findViewById(R.id.indicator);
          adapter = new TabsAdapter(getSupportFragmentManager(), false);
  
          adapter.addFragment(new FirstFragment());
          adapter.addFragment(new SecondFragment());
          indicator.notifyDataSetChanged();
          adapter.notifyDataSetChanged();
  
          // push first task
          FirstTask firstTask = new FirstTask(MyActivity.this);
          // set first fragment as listener
          firstTask.setTaskListener((TaskListener) adapter.getItem(0));
          firstTask.execute();
      }
  
      indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener()  {
          @Override
          public void onPageSelected(int position) {
              Fragment currentFragment = adapter.getItem(position);
              ((Taskable) currentFragment).executeTask();
          }
  
          @Override
          public void onPageScrolled(int i, float v, int i1) {}
  
          @Override
          public void onPageScrollStateChanged(int i) {}
      });
  }
  </code></pre>
  
  <p>AsyncTask class</p>
  
  <pre><code>public class FirstTask extends AsyncTask{
  
      private TaskListener taskListener;
  
      ...
  
      @Override
      protected void onPostExecute(T result) {
          ... 
          taskListener.onTaskComplete(result);
      }   
  }
  </code></pre>
  
  <p>Fragment class</p>
  
  <pre><code>public class FirstFragment extends Fragment immplements Taskable, TaskListener{
  
      public FirstFragment() {
      }
  
      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
          return inflater.inflate(R.layout.first_view, container, false);
      }
  
      @Override
      public void executeTask() {
          FirstTask firstTask = new FirstTask(MyActivity.this);
          firstTask.setTaskListener(this);
          firstTask.execute();
      }
  
      @Override
      public void onTaskComplete(T result) {
          // NPE is here 
          Resources res = getActivity().getResources();
          ...
      }
  }
  </code></pre>
  
  <p>Maybe this error happens when applications resumed from background. In this case how I should handle this situation properly?</p>