Solution to the problem of Android getActivity() being empty
In development projects, you sometimes encounter the situation where the getActivity function is empty, which leads to the apk null pointer crash. There is no obvious reason for the code logic.
If you look at the source code, you can find the reason. When the activity instance is in the background, the system is likely to reclaim the activity when reclaiming resources, and save the fragment state in the onSaveInstanceState function. When opening the activity again, the fragment state in the bundle is taken out in the onCreate method, but the activity corresponding to the fragment is no longer there, so the getActivity is empty.
Excerpted from:
protected void onCreate(Bundle savedInstanceState) { ....... if (savedInstanceState != null) { Parcelable p = (FRAGMENTS_TAG); (p, nc != null ? : null); } (); } protected void onSaveInstanceState(Bundle outState) { (outState); Parcelable p = (); if (p != null) { (FRAGMENTS_TAG, p); } }
The solution can be seen from the source code: 1. Overwrite the onSaveInstanceState function and do not save it to the bundle; 2. Overwrite the onCreate method and delete the FRAGMENTS_TAG parameter. (Note: Activity and FragmentActivity define FRAGMENTS_TAG differently)
For example:
public class TestActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { if (savedInstanceState != null) { ("android:support:fragments"); //Note: When the base class is Activity, the parameter is android:fragments, and it must be executed in front of the function! ! ! } (savedInstanceState); ... } //or protected void onSaveInstanceState(Bundle outState) { //(outState); //Comment out this method, that is, the state is not saved }
The above is an explanation of the solution to the problem of Android getActivity() being empty. If you have any questions, please leave a message or discuss it in this website community. Thank you for reading. I hope it can help you. Thank you for your support for this website!