Search code examples
androidandroid-activitystaticmvp

What happens to static members of an Activity when it is recreated because of config changes


I want to create a static presenter object in my Activity, so that when the Activity is recreated because of config changes, it will retain the presenter instance and my business logic will not be affected.

The code of my Activity is:

    public class HomeActivity extends AppCompatActivity {

    public static HomePresenter presenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        if (presenter == null){
            presenter = new HomePresenter();
        }
    }
}

Solution

  • Nothing will happen to the static instance. But doing this could leak memory (see Avoiding memory leaks) if you do not delete the reference to the static presenter.

    I would suggest another approach. Override onRetainNonConfigurationInstance() to keep an object when the Activity is destroyed because of an configuration change (e.g. rotation). And use getLastNonConfigurationInstance() to get the very same object after the configuration change.

     public class HomeActivity extends AppCompatActivity {
    
        public HomePresenter presenter;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_home);
    
            presenter = (HomePresenter)getLastNonConfigurationInstance();
            if (presenter == null){
                presenter = new HomePresenter();
            }
        }
    
        @Override
        public Object onRetainNonConfigurationInstance() {
            return presenter;
        }
    }
    

    You can also use a Fragment to keep objects alive during a configuration change, see RetainingAnObject.