The getActivity of fragment is empty because the Activity is recycled. fragmentgetactivity

Source: Internet
Author: User

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!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.