title: General guidelines for calling getActivity() inside DialogFragment class
body: <p>As mentioned <a href="http://developer.android.com/guide/components/fragments.html#Lifecycle" rel="noreferrer">here</a>:</p>
  
  <p>"<em><code>be careful to call getActivity() only when the fragment is attached to an activity. When the fragment is not yet attached, or was detached during the end of its lifecycle, getActivity() will return null.</code></em>"</p>
  
  <hr>
  
  <p>I have a couple of questions regarding calling <a href="http://developer.android.com/reference/android/support/v4/app/Fragment.html#getActivity()" rel="noreferrer">getActivity()</a> inside <a href="http://developer.android.com/reference/android/app/DialogFragment.html" rel="noreferrer">DialogFragment</a>. </p>
  
  <ol>
  <li><p><strong>What are different scenarios under which a DialogFragment can unexpectedly get detached from its parent Activity or didn't attach at the first place?</strong> The thing is I am calling getActivity() inside onPositiveButtonClick's listener and have received a couple of crash reports (Null pointer exception) for it. I am unable to reproduce the crash, screen orientation doesn't seem to do the trick.</p></li>
  <li><p><strong>What are some recommended guidelines on how to use getActivity() with minimal damage?</strong> I have read some other stackoverflow posts which suggest</p>
  
  <p>a) Override onAttach() method.<br>
  <code>public void onAttach(Activity activity) {
      super.onAttach(activity);
      mActivity = activity;
  }</code></p>
  
  <p>I would prefer this less as it keeps an instance of the Activity. Also, how can I be sure local instance of the activity is never set to null. Would like to know the pros and cons before using it.</p>
  
  <p>b)  Will delegating the onClick() implementations to the calling activity using an interface help? If yes, how?</p></li>
  </ol>
  
  <hr>
  
  <p>If all of this is unavoidable, I don't see a better alternative than letting the app crash. I can't show a toast since getActivity() is null and would avoid letting the onClick operation fail silently.</p>
  
  <p>Any pointers would be much appreciated. Thank you!</p>