Solution of getactivity NULL for fragment caused by activity being recycled

Source: Internet
Author: User

These two days have been plagued by this problem, if the app is running in the background for a long time, then click into will crash, and fragment page overlap phenomenon, let me very uncomfortable. Study the day and finally understand the principles and solve them. The solution is as follows:

if the system is out of memory, or switching between the screen, or the app is running in the background for a long time, the activity may be reclaimed by the system, and then fragment will not be recycled as the activity is recycled, resulting in fragment losing the corresponding activity.

Here, suppose we inherit from the Fragmentactivity class as Mainactivity, which uses the fragment as Fragmenta.

The app changes: For some reason system recovery mainactivity--Fragmenta is not recycled--click on the app again--first loaded is the non-recycled fragmenta page -- Because mainactivity is recycled , the system restarts mainactivity andFragmenta is reloaded again-the page is cluttered because a layer of non-recyclable The Fragmenta is covered on top of it-(if Fragmenta uses the Getactivity () method ) It will report a null pointer, and a crash appears.

Although the principle is a bit around, the solution is simple:

mainactivity Rewrite the Onsaveinstancestate method, Super.onsaveinstancestate (outstate), comment out , let it no longer save fragment state, Achieve the effect of being recycled along with mainactivity!

Solution of getactivity NULL for fragment caused by activity being recycled

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.