The getActivity of fragment is empty because the Activity is recycled. fragmentgetactivity
This is often the case when writing code containing Fragment. If the app runs in the background for a long time, then clicking it will crash, and the fragment page will overlap.
If the system memory is insufficient, the screen is switched, or the app runs in the background for a long time, the Activity may be recycled by the system, and Fragment will not be recycled as the Activity is recycled, as a result, Fragment loses the corresponding Activity.
Here, we assume that we have a MainActivity that contains a FramentA.
App changes: the app runs on the background for a long time, for some reason, the system recycles MainActivity -- FragmentA is saved and not recycled -- click the app again to enter -- the first load is the unrecycled FragmentA page -- Because MainActivity is recycled, the system restarts MainActivity, fragmentA will also be loaded again -- the page will be messy, because a layer of unrecycled FragmentA will overwrite it -- (if FragmentA uses the getActivity () method), a null pointer will be reported and crash will appear.
In this case, we can solve the problem as follows:
MainActivity overwrites the onSaveInstanceState method and comment out super. onSaveInstanceState (outState); so that it does not save the Fragment State, so that it will be recycled along with MainActivity!