Solution to the problem that Android getactivity() is empty
Solution to the problem that Android getactivity() is empty
In development projects, sometimes the getactivity function is null, resulting in APK null pointer crash. There is no obvious reason for the code logic.
If you look at the source code of activity. Java and fragmentactivity. Java, you can find the reason. When the activity instance is in the background, the system is likely to recycle the activity when recycling resources and save the fragment state in the onsaveinstancestate function. When the activity is opened again, the fragment state in the bundle is taken out in the oncreate method, but the activity corresponding to the fragment has long disappeared, so getactivity is empty.
From fragmentactivity.java:
From the source code, we can see the solution: 1. Overwrite the onsaveinstancestate function and do not save it to the bundle; 2. Override the oncreate method and delete fragments_ Tag parameter. (Note: activities and fragmentactivities have different definitions of fragments_tag)
For example:
The above is the explanation of the solution to the problem that Android getactivity() is empty. If you have any questions, please leave a message or discuss in the community of this site. Thank you for reading. I hope it can help you. Thank you for your support to this site!