title: Android - getActivity and Activity life cycle
body: <p>If I have the following code in a Fragment:</p>
  
  <pre><code>public void doSomething() {
      if (getActivity() == null)
          return; // no null pointer exceptions here!
      // ...
      // do bunch of stuff here
      // ...
  
      getActivity().setTitle("done something"); // just whatever
  }
  </code></pre>
  
  <p>As you can see, at the beginning of the method I check if getActivity() is null and return if it is.  However, if it is not null, the method continues executing.  At the end, I call getActivity() again to set title, however I don't check if getActivity() is null.  Theoretically, it's possible at this point the Fragment has been detached from the Activity so it's possible getActivity() could be null and therefore the last line will throw a NullPointerException. What is the solution for this? Check if getActivity() is null every time I want to call it?</p>
  
  <p>Edit:  Even if we try this, it's possible to get a NPE - I just called getActivity() each time to simplify the example:</p>
  
  <pre><code>public void doSomething() {
      Activity activity = getActivity();
      if (activity == null)
          return; // no null pointer exceptions here!
      // ...
      // do bunch of stuff here
      // ...
  
      activity.setTitle("done something"); // just whatever
  }
  </code></pre>
  
  <p>The problem is not that the Activity hasn't finished loading yet - this can happen minutes after load for instance, as a response to any event.  The problem is not the FIRST call to getActivity, it's that in the 15 lines or so from the time we check if activity is null to the last time we reference it, it can no longer exist.</p>
  
  <p>I don't have a logcat right now, but this is what is happening.  We haven't really seen this ourselves, but this is for an app where this function is being called thousands of times a day, so it's possible to happen once in a while to someone.</p>
  
  <p>Edit 2:  What I'm currently doing is trying and catching for NPEs and just not doing something if it fails. However it seems like an ugly way to solve the problem - I'm wondering if there's a better solution!</p>