General guidelines for calling getActivity () inside the DialogFragment class

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 few questions regarding calling getActivity () inside DialogFragment .

  • What are the different scenarios in which DialogFragment may unexpectedly disconnect from its parent activity or not be attached in the first place? The thing is, I call getActivity () inside the onPositiveButtonClick listener and got a couple of crash reports (Null pointer exception) for it. I can not reproduce the crash, the screen orientation does not seem to be a trick.

  • What are the recommended guidelines for using getActivity () with minimal damage? I read some other stackoverflow posts that suggest

    a) Override the onAttach () method.
    public void onAttach(Activity activity) { super.onAttach(activity); mActivity = activity; }

    I would prefer this less because it stores an instance of Activity. Also, how can I be sure that the local activity instance is never set to null. I would like to know the pros and cons before using it.

    b) Will delegation of the onClick () implementation of the calling activity be done using the interface? If so, how?


If all this is inevitable, I see no better alternative than to crash the application. I cannot show a toast, since getActivity () is NULL and avoids the inactive onClick operation.

Any pointers would be much appreciated. Thanks!

+5
source share

Source: https://habr.com/ru/post/1241903/


All Articles