As mentioned here:
"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.
"
I have a couple of questions regarding calling getActivity() inside DialogFragment.
What are different scenarios under which a DialogFragment can unexpectedly get detached from its parent Activity or didn't attach at the first place? 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.
What are some recommended guidelines on how to use getActivity() with minimal damage? I have read some other stackoverflow posts which suggest
a) Override onAttach() method.
public void onAttach(Activity activity) { super.onAttach(activity); mActivity = activity; }
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.
b) Will delegating the onClick() implementations to the calling activity using an interface help? If yes, how?
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.
Any pointers would be much appreciated. Thank you!